1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
12 use crate::rustc::hir::*;
13 use crate::rustc::hir::intravisit::FnKind;
14 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use crate::rustc::{declare_tool_lint, lint_array};
16 use if_chain::if_chain;
17 use crate::rustc::ty::{self, RegionKind, TypeFoldable};
18 use crate::rustc::traits;
19 use crate::rustc::middle::expr_use_visitor as euv;
20 use crate::rustc::middle::mem_categorization as mc;
21 use crate::rustc_target::spec::abi::Abi;
22 use crate::rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use crate::syntax::ast::NodeId;
24 use crate::syntax_pos::Span;
25 use crate::syntax::errors::DiagnosticBuilder;
26 use crate::utils::{get_trait_def_id, implements_trait, in_macro, is_copy, is_self, match_type, multispan_sugg, paths,
27 snippet, snippet_opt, span_lint_and_then};
28 use crate::utils::ptr::get_spans;
30 use crate::rustc_errors::Applicability;
32 /// **What it does:** Checks for functions taking arguments by value, but not
33 /// consuming them in its
36 /// **Why is this bad?** Taking arguments by reference is more flexible and can
38 /// unnecessary allocations.
40 /// **Known problems:**
41 /// * This lint suggests taking an argument by reference,
42 /// however sometimes it is better to let users decide the argument type
43 /// (by using `Borrow` trait, for example), depending on how the function is used.
47 /// fn foo(v: Vec<i32>) {
48 /// assert_eq!(v.len(), 42);
51 /// fn foo(v: &[i32]) {
52 /// assert_eq!(v.len(), 42);
55 declare_clippy_lint! {
56 pub NEEDLESS_PASS_BY_VALUE,
58 "functions taking arguments by value, but not consuming them in its body"
61 pub struct NeedlessPassByValue;
63 impl LintPass for NeedlessPassByValue {
64 fn get_lints(&self) -> LintArray {
65 lint_array![NEEDLESS_PASS_BY_VALUE]
70 ($e: expr) => { if let Some(x) = $e { x } else { return; } };
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
76 cx: &LateContext<'a, 'tcx>,
88 FnKind::ItemFn(.., header, _, attrs) => {
89 if header.abi != Abi::Rust {
93 if a.meta_item_list().is_some() && a.name() == "proc_macro_derive" {
98 FnKind::Method(..) => (),
102 // Exclude non-inherent impls
103 if let Some(Node::Item(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(node_id)) {
104 if matches!(item.node, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
111 // Allow `Borrow` or functions to be taken by value
112 let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
113 let whitelisted_traits = [
114 need!(cx.tcx.lang_items().fn_trait()),
115 need!(cx.tcx.lang_items().fn_once_trait()),
116 need!(cx.tcx.lang_items().fn_mut_trait()),
117 need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT))
120 let sized_trait = need!(cx.tcx.lang_items().sized_trait());
122 let fn_def_id = cx.tcx.hir.local_def_id(node_id);
124 let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
125 .filter(|p| !p.is_global())
127 if let ty::Predicate::Trait(poly_trait_ref) = pred {
128 if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_regions() {
136 .collect::<Vec<_>>();
138 // Collect moved variables and spans which will need dereferencings from the
140 let MovedVariablesCtxt {
145 let mut ctx = MovedVariablesCtxt::new(cx);
146 let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
147 euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None)
152 let fn_sig = cx.tcx.fn_sig(fn_def_id);
153 let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
155 for (idx, ((input, &ty), arg)) in decl.inputs
157 .zip(fn_sig.inputs())
158 .zip(&body.arguments)
161 // All spans generated from a proc-macro invocation are the same...
162 if span == input.span {
168 if let PatKind::Binding(_, _, ident, ..) = arg.pat.node {
169 if ident.as_str() == "self" {
175 // * Exclude a type that is specifically bounded by `Borrow`.
176 // * Exclude a type whose reference also fulfills its bound.
177 // (e.g. `std::convert::AsRef`, `serde::Serialize`)
178 let (implements_borrow_trait, all_borrowable_trait) = {
181 .filter(|t| t.skip_binder().self_ty() == ty)
182 .collect::<Vec<_>>();
185 preds.iter().any(|t| t.def_id() == borrow_trait),
186 !preds.is_empty() && preds.iter().all(|t| {
187 let ty_params = &t.skip_binder().trait_ref.substs.iter().skip(1)
189 .collect::<Vec<_>>();
192 cx.tcx.mk_imm_ref(&RegionKind::ReErased, ty),
202 if !ty.is_mutable_pointer();
204 if !whitelisted_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
205 if !implements_borrow_trait;
206 if !all_borrowable_trait;
208 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.node;
209 if !moved_vars.contains(&canonical_id);
211 if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
215 // Dereference suggestion
216 let sugg = |db: &mut DiagnosticBuilder<'_>| {
217 if let ty::TyKind::Adt(def, ..) = ty.sty {
218 if let Some(span) = cx.tcx.hir.span_if_local(def.did) {
219 if cx.param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
220 db.span_help(span, "consider marking this type as Copy");
225 let deref_span = spans_need_deref.get(&canonical_id);
227 if match_type(cx, ty, &paths::VEC);
228 if let Some(clone_spans) =
229 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
230 if let TyKind::Path(QPath::Resolved(_, ref path)) = input.node;
231 if let Some(elem_ty) = path.segments.iter()
232 .find(|seg| seg.ident.name == "Vec")
233 .and_then(|ps| ps.args.as_ref())
234 .map(|params| params.args.iter().find_map(|arg| match arg {
235 GenericArg::Type(ty) => Some(ty),
236 GenericArg::Lifetime(_) => None,
239 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
240 db.span_suggestion_with_applicability(
242 "consider changing the type to",
244 Applicability::Unspecified,
247 for (span, suggestion) in clone_spans {
248 db.span_suggestion_with_applicability(
250 &snippet_opt(cx, span)
252 "change the call to".into(),
253 |x| Cow::from(format!("change `{}` to", x)),
256 Applicability::Unspecified,
260 // cannot be destructured, no need for `*` suggestion
261 assert!(deref_span.is_none());
266 if match_type(cx, ty, &paths::STRING) {
267 if let Some(clone_spans) =
268 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
269 db.span_suggestion_with_applicability(
271 "consider changing the type to",
273 Applicability::Unspecified,
276 for (span, suggestion) in clone_spans {
277 db.span_suggestion_with_applicability(
279 &snippet_opt(cx, span)
281 "change the call to".into(),
282 |x| Cow::from(format!("change `{}` to", x))
285 Applicability::Unspecified,
289 assert!(deref_span.is_none());
294 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
296 // Suggests adding `*` to dereference the added reference.
297 if let Some(deref_span) = deref_span {
302 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
304 spans.sort_by_key(|&(span, _)| span);
306 multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
311 NEEDLESS_PASS_BY_VALUE,
313 "this argument is passed by value, but not consumed in the function body",
322 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
323 cx: &'a LateContext<'a, 'tcx>,
324 moved_vars: FxHashSet<NodeId>,
325 /// Spans which need to be prefixed with `*` for dereferencing the
326 /// suggested additional reference.
327 spans_need_deref: FxHashMap<NodeId, 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: NodeId, _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.id;
353 let parent = self.cx.tcx.hir.get_parent_node(id);
360 if let Some(node) = self.cx.tcx.hir.find(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::Decl(ref decl, _) = s.node;
376 if let DeclKind::Local(ref local) = decl.node;
378 self.spans_need_deref
380 .or_insert_with(FxHashSet::default)
384 .expect("`let` stmt without init aren't caught by match_pat"));
397 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
398 fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
399 if let euv::ConsumeMode::Move(_) = mode {
400 self.move_common(consume_id, consume_span, cmt);
404 fn matched_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::MatchMode) {
405 if let euv::MatchMode::MovingMatch = mode {
406 self.move_common(matched_pat.id, matched_pat.span, cmt);
408 self.non_moving_pat(matched_pat, cmt);
412 fn consume_pat(&mut self, consume_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
413 if let euv::ConsumeMode::Move(_) = mode {
414 self.move_common(consume_pat.id, consume_pat.span, cmt);
418 fn borrow(&mut self, _: NodeId, _: Span, _: &mc::cmt_<'tcx>, _: ty::Region<'_>, _: ty::BorrowKind, _: euv::LoanCause) {}
420 fn mutate(&mut self, _: NodeId, _: Span, _: &mc::cmt_<'tcx>, _: euv::MutateMode) {}
422 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
426 fn unwrap_downcast_or_interior<'a, 'tcx>(mut cmt: &'a mc::cmt_<'tcx>) -> mc::cmt_<'tcx> {
429 mc::Categorization::Downcast(ref c, _) | mc::Categorization::Interior(ref c, _) => {
432 _ => return (*cmt).clone(),