3 use rustc::hir::map::*;
4 use rustc::hir::intravisit::FnKind;
6 use rustc::{declare_lint, lint_array};
7 use if_chain::if_chain;
8 use rustc::ty::{self, RegionKind, TypeFoldable};
10 use rustc::middle::expr_use_visitor as euv;
11 use rustc::middle::mem_categorization as mc;
12 use rustc_target::spec::abi::Abi;
13 use syntax::ast::NodeId;
15 use syntax::errors::DiagnosticBuilder;
16 use crate::utils::{get_trait_def_id, implements_trait, in_macro, is_copy, is_self, match_type, multispan_sugg, paths,
17 snippet, snippet_opt, span_lint_and_then};
18 use crate::utils::ptr::get_spans;
19 use std::collections::{HashMap, HashSet};
22 /// **What it does:** Checks for functions taking arguments by value, but not
23 /// consuming them in its
26 /// **Why is this bad?** Taking arguments by reference is more flexible and can
28 /// unnecessary allocations.
30 /// **Known problems:**
31 /// * This lint suggests taking an argument by reference,
32 /// however sometimes it is better to let users decide the argument type
33 /// (by using `Borrow` trait, for example), depending on how the function is used.
37 /// fn foo(v: Vec<i32>) {
38 /// assert_eq!(v.len(), 42);
41 /// fn foo(v: &[i32]) {
42 /// assert_eq!(v.len(), 42);
45 declare_clippy_lint! {
46 pub NEEDLESS_PASS_BY_VALUE,
48 "functions taking arguments by value, but not consuming them in its body"
51 pub struct NeedlessPassByValue;
53 impl LintPass for NeedlessPassByValue {
54 fn get_lints(&self) -> LintArray {
55 lint_array![NEEDLESS_PASS_BY_VALUE]
60 ($e: expr) => { if let Some(x) = $e { x } else { return; } };
63 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
66 cx: &LateContext<'a, 'tcx>,
78 FnKind::ItemFn(.., header, _, attrs) => {
79 if header.abi != Abi::Rust {
83 if a.meta_item_list().is_some() && a.name() == "proc_macro_derive" {
88 FnKind::Method(..) => (),
92 // Exclude non-inherent impls
93 if let Some(NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(node_id)) {
94 if matches!(item.node, ItemKind::Impl(_, _, _, _, 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 whitelisted_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(node_id);
114 let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
115 .filter(|p| !p.is_global())
117 if let ty::Predicate::Trait(poly_trait_ref) = pred {
118 if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_regions() {
126 .collect::<Vec<_>>();
128 // Collect moved variables and spans which will need dereferencings from the
130 let MovedVariablesCtxt {
135 let mut ctx = MovedVariablesCtxt::new(cx);
136 let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
137 euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None)
142 let fn_sig = cx.tcx.fn_sig(fn_def_id);
143 let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
145 for (idx, ((input, &ty), arg)) in decl.inputs
147 .zip(fn_sig.inputs())
148 .zip(&body.arguments)
151 // All spans generated from a proc-macro invocation are the same...
152 if span == input.span {
158 if let PatKind::Binding(_, _, ident, ..) = arg.pat.node {
159 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.
167 // (e.g. `std::convert::AsRef`, `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),
176 !preds.is_empty() && preds.iter().all(|t| {
179 cx.tcx.mk_imm_ref(&RegionKind::ReErased, ty),
185 .collect::<Vec<_>>(),
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::TypeVariants::TyAdt(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, &[("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 == "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),
227 GenericArg::Lifetime(_) => None,
230 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
231 db.span_suggestion(input.span,
232 "consider changing the type to",
235 for (span, suggestion) in clone_spans {
238 &snippet_opt(cx, span)
240 "change the call to".into(),
241 |x| Cow::from(format!("change `{}` to", x)),
247 // cannot be destructured, no need for `*` suggestion
248 assert!(deref_span.is_none());
253 if match_type(cx, ty, &paths::STRING) {
254 if let Some(clone_spans) =
255 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
256 db.span_suggestion(input.span, "consider changing the type to", "&str".to_string());
258 for (span, suggestion) in clone_spans {
261 &snippet_opt(cx, span)
263 "change the call to".into(),
264 |x| Cow::from(format!("change `{}` to", x))
270 assert!(deref_span.is_none());
275 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
277 // Suggests adding `*` to dereference the added reference.
278 if let Some(deref_span) = deref_span {
283 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
285 spans.sort_by_key(|&(span, _)| span);
287 multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
292 NEEDLESS_PASS_BY_VALUE,
294 "this argument is passed by value, but not consumed in the function body",
303 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
304 cx: &'a LateContext<'a, 'tcx>,
305 moved_vars: HashSet<NodeId>,
306 /// Spans which need to be prefixed with `*` for dereferencing the
307 /// suggested additional reference.
308 spans_need_deref: HashMap<NodeId, HashSet<Span>>,
311 impl<'a, 'tcx> MovedVariablesCtxt<'a, 'tcx> {
312 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
315 moved_vars: HashSet::new(),
316 spans_need_deref: HashMap::new(),
320 fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: &mc::cmt_<'tcx>) {
321 let cmt = unwrap_downcast_or_interior(cmt);
323 if let mc::Categorization::Local(vid) = cmt.cat {
324 self.moved_vars.insert(vid);
328 fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>) {
329 let cmt = unwrap_downcast_or_interior(cmt);
331 if let mc::Categorization::Local(vid) = cmt.cat {
332 let mut id = matched_pat.id;
334 let parent = self.cx.tcx.hir.get_parent_node(id);
341 if let Some(node) = self.cx.tcx.hir.find(id) {
343 map::Node::NodeExpr(e) => {
344 // `match` and `if let`
345 if let ExprKind::Match(ref c, ..) = e.node {
346 self.spans_need_deref
348 .or_insert_with(HashSet::new)
353 map::Node::NodeStmt(s) => {
356 if let StmtKind::Decl(ref decl, _) = s.node;
357 if let DeclKind::Local(ref local) = decl.node;
359 self.spans_need_deref
361 .or_insert_with(HashSet::new)
365 .expect("`let` stmt without init aren't caught by match_pat"));
378 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
379 fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
380 if let euv::ConsumeMode::Move(_) = mode {
381 self.move_common(consume_id, consume_span, cmt);
385 fn matched_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::MatchMode) {
386 if let euv::MatchMode::MovingMatch = mode {
387 self.move_common(matched_pat.id, matched_pat.span, cmt);
389 self.non_moving_pat(matched_pat, cmt);
393 fn consume_pat(&mut self, consume_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
394 if let euv::ConsumeMode::Move(_) = mode {
395 self.move_common(consume_pat.id, consume_pat.span, cmt);
399 fn borrow(&mut self, _: NodeId, _: Span, _: &mc::cmt_<'tcx>, _: ty::Region, _: ty::BorrowKind, _: euv::LoanCause) {}
401 fn mutate(&mut self, _: NodeId, _: Span, _: &mc::cmt_<'tcx>, _: euv::MutateMode) {}
403 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
407 fn unwrap_downcast_or_interior<'a, 'tcx>(mut cmt: &'a mc::cmt_<'tcx>) -> mc::cmt_<'tcx> {
410 mc::Categorization::Downcast(ref c, _) | mc::Categorization::Interior(ref c, _) => {
413 _ => return (*cmt).clone(),