1 use crate::utils::ptr::get_spans;
4 get_trait_def_id, implements_trait, in_macro_or_desugar, is_copy, is_self, match_type, multispan_sugg, paths,
5 snippet, snippet_opt, span_lint_and_then,
7 use if_chain::if_chain;
9 use rustc::hir::intravisit::FnKind;
11 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use rustc::middle::expr_use_visitor as euv;
13 use rustc::middle::mem_categorization as mc;
15 use rustc::ty::{self, RegionKind, TypeFoldable};
16 use rustc::{declare_lint_pass, declare_tool_lint};
17 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
18 use rustc_errors::Applicability;
19 use rustc_target::spec::abi::Abi;
21 use syntax::ast::Attribute;
22 use syntax::errors::DiagnosticBuilder;
25 declare_clippy_lint! {
26 /// **What it does:** Checks for functions taking arguments by value, but not
27 /// consuming them in its
30 /// **Why is this bad?** Taking arguments by reference is more flexible and can
32 /// unnecessary allocations.
34 /// **Known problems:**
35 /// * This lint suggests taking an argument by reference,
36 /// however sometimes it is better to let users decide the argument type
37 /// (by using `Borrow` trait, for example), depending on how the function is used.
41 /// fn foo(v: Vec<i32>) {
42 /// assert_eq!(v.len(), 42);
45 /// fn foo(v: &[i32]) {
46 /// assert_eq!(v.len(), 42);
49 pub NEEDLESS_PASS_BY_VALUE,
51 "functions taking arguments by value, but not consuming them in its body"
54 declare_lint_pass!(NeedlessPassByValue => [NEEDLESS_PASS_BY_VALUE]);
66 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
67 #[allow(clippy::too_many_lines)]
70 cx: &LateContext<'a, 'tcx>,
77 if in_macro_or_desugar(span) {
82 FnKind::ItemFn(.., header, _, attrs) => {
83 if header.abi != Abi::Rust || requires_exact_signature(attrs) {
87 FnKind::Method(..) => (),
91 // Exclude non-inherent impls
92 if let Some(Node::Item(item)) = cx
95 .find_by_hir_id(cx.tcx.hir().get_parent_node_by_hir_id(hir_id))
97 if matches!(item.node, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
104 // Allow `Borrow` or functions to be taken by value
105 let borrow_trait = need!(get_trait_def_id(cx, &*paths::BORROW_TRAIT));
106 let whitelisted_traits = [
107 need!(cx.tcx.lang_items().fn_trait()),
108 need!(cx.tcx.lang_items().fn_once_trait()),
109 need!(cx.tcx.lang_items().fn_mut_trait()),
110 need!(get_trait_def_id(cx, &*paths::RANGE_ARGUMENT_TRAIT)),
113 let sized_trait = need!(cx.tcx.lang_items().sized_trait());
115 let fn_def_id = cx.tcx.hir().local_def_id_from_hir_id(hir_id);
117 let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
118 .filter(|p| !p.is_global())
120 if let ty::Predicate::Trait(poly_trait_ref) = pred {
121 if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_bound_vars()
130 .collect::<Vec<_>>();
132 // Collect moved variables and spans which will need dereferencings from the
134 let MovedVariablesCtxt {
139 let mut ctx = MovedVariablesCtxt::new(cx);
140 let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
141 euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None)
146 let fn_sig = cx.tcx.fn_sig(fn_def_id);
147 let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
149 for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments).enumerate() {
150 // All spans generated from a proc-macro invocation are the same...
151 if span == input.span {
157 if let PatKind::Binding(.., ident, _) = arg.pat.node {
158 if ident.as_str() == "self" {
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) = {
171 .filter(|t| t.skip_binder().self_ty() == ty)
172 .collect::<Vec<_>>();
175 preds.iter().any(|t| t.def_id() == borrow_trait),
177 && preds.iter().all(|t| {
185 .collect::<Vec<_>>();
186 implements_trait(cx, cx.tcx.mk_imm_ref(&RegionKind::ReEmpty, ty), t.def_id(), ty_params)
193 if !ty.is_mutable_pointer();
195 if !whitelisted_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
196 if !implements_borrow_trait;
197 if !all_borrowable_trait;
199 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.node;
200 if !moved_vars.contains(&canonical_id);
202 if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
206 // Dereference suggestion
207 let sugg = |db: &mut DiagnosticBuilder<'_>| {
208 if let ty::Adt(def, ..) = ty.sty {
209 if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
210 if cx.param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
211 db.span_help(span, "consider marking this type as Copy");
216 let deref_span = spans_need_deref.get(&canonical_id);
218 if match_type(cx, ty, &*paths::VEC);
219 if let Some(clone_spans) =
220 get_spans(cx, Some(body.id()), idx, &[(*sym::clone, ".to_owned()")]);
221 if let TyKind::Path(QPath::Resolved(_, ref path)) = input.node;
222 if let Some(elem_ty) = path.segments.iter()
223 .find(|seg| seg.ident.name == *sym::Vec)
224 .and_then(|ps| ps.args.as_ref())
225 .map(|params| params.args.iter().find_map(|arg| match arg {
226 GenericArg::Type(ty) => Some(ty),
230 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
233 "consider changing the type to",
235 Applicability::Unspecified,
238 for (span, suggestion) in clone_spans {
241 &snippet_opt(cx, span)
243 "change the call to".into(),
244 |x| Cow::from(format!("change `{}` to", x)),
247 Applicability::Unspecified,
251 // cannot be destructured, no need for `*` suggestion
252 assert!(deref_span.is_none());
257 if match_type(cx, ty, &*paths::STRING) {
258 if let Some(clone_spans) =
259 get_spans(cx, Some(body.id()), idx, &[(*sym::clone, ".to_string()"), (*sym::as_str, "")]) {
262 "consider changing the type to",
264 Applicability::Unspecified,
267 for (span, suggestion) in clone_spans {
270 &snippet_opt(cx, span)
272 "change the call to".into(),
273 |x| Cow::from(format!("change `{}` to", x))
276 Applicability::Unspecified,
280 assert!(deref_span.is_none());
285 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
287 // Suggests adding `*` to dereference the added reference.
288 if let Some(deref_span) = deref_span {
293 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
295 spans.sort_by_key(|&(span, _)| span);
297 multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
302 NEEDLESS_PASS_BY_VALUE,
304 "this argument is passed by value, but not consumed in the function body",
313 /// Functions marked with these attributes must have the exact signature.
314 fn requires_exact_signature(attrs: &[Attribute]) -> bool {
315 attrs.iter().any(|attr| {
316 [*sym::proc_macro, *sym::proc_macro_attribute, *sym::proc_macro_derive]
318 .any(|&allow| attr.check_name(allow))
322 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
323 cx: &'a LateContext<'a, 'tcx>,
324 moved_vars: FxHashSet<HirId>,
325 /// Spans which need to be prefixed with `*` for dereferencing the
326 /// suggested additional reference.
327 spans_need_deref: FxHashMap<HirId, FxHashSet<Span>>,
330 impl<'a, 'tcx> MovedVariablesCtxt<'a, 'tcx> {
331 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
334 moved_vars: FxHashSet::default(),
335 spans_need_deref: FxHashMap::default(),
339 fn move_common(&mut self, _consume_id: HirId, _span: Span, cmt: &mc::cmt_<'tcx>) {
340 let cmt = unwrap_downcast_or_interior(cmt);
342 if let mc::Categorization::Local(vid) = cmt.cat {
343 self.moved_vars.insert(vid);
347 fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>) {
348 let cmt = unwrap_downcast_or_interior(cmt);
350 if let mc::Categorization::Local(vid) = cmt.cat {
351 let mut id = matched_pat.hir_id;
353 let parent = self.cx.tcx.hir().get_parent_node_by_hir_id(id);
360 if let Some(node) = self.cx.tcx.hir().find_by_hir_id(id) {
363 // `match` and `if let`
364 if let ExprKind::Match(ref c, ..) = e.node {
365 self.spans_need_deref
367 .or_insert_with(FxHashSet::default)
375 if let StmtKind::Local(ref local) = s.node;
377 self.spans_need_deref
379 .or_insert_with(FxHashSet::default)
383 .expect("`let` stmt without init aren't caught by match_pat"));
396 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
397 fn consume(&mut self, consume_id: HirId, consume_span: Span, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
398 if let euv::ConsumeMode::Move(_) = mode {
399 self.move_common(consume_id, consume_span, cmt);
403 fn matched_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::MatchMode) {
404 if let euv::MatchMode::MovingMatch = mode {
405 self.move_common(matched_pat.hir_id, matched_pat.span, cmt);
407 self.non_moving_pat(matched_pat, cmt);
411 fn consume_pat(&mut self, consume_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
412 if let euv::ConsumeMode::Move(_) = mode {
413 self.move_common(consume_pat.hir_id, consume_pat.span, cmt);
428 fn mutate(&mut self, _: HirId, _: Span, _: &mc::cmt_<'tcx>, _: euv::MutateMode) {}
430 fn decl_without_init(&mut self, _: HirId, _: Span) {}
433 fn unwrap_downcast_or_interior<'a, 'tcx>(mut cmt: &'a mc::cmt_<'tcx>) -> mc::cmt_<'tcx> {
436 mc::Categorization::Downcast(ref c, _) | mc::Categorization::Interior(ref c, _) => {
439 _ => return (*cmt).clone(),