2 use rustc::hir::map::*;
3 use rustc::hir::intravisit::FnKind;
5 use rustc::ty::{self, RegionKind, TypeFoldable};
7 use rustc::middle::expr_use_visitor as euv;
8 use rustc::middle::mem_categorization as mc;
9 use rustc_target::spec::abi::Abi;
10 use syntax::ast::NodeId;
12 use syntax::errors::DiagnosticBuilder;
13 use utils::{get_trait_def_id, implements_trait, in_macro, is_copy, is_self, match_type, multispan_sugg, paths,
14 snippet, snippet_opt, span_lint_and_then};
15 use utils::ptr::get_spans;
16 use std::collections::{HashMap, HashSet};
19 /// **What it does:** Checks for functions taking arguments by value, but not
20 /// consuming them in its
23 /// **Why is this bad?** Taking arguments by reference is more flexible and can
25 /// unnecessary allocations.
27 /// **Known problems:**
28 /// * This lint suggests taking an argument by reference,
29 /// however sometimes it is better to let users decide the argument type
30 /// (by using `Borrow` trait, for example), depending on how the function is used.
34 /// fn foo(v: Vec<i32>) {
35 /// assert_eq!(v.len(), 42);
38 /// fn foo(v: &[i32]) {
39 /// assert_eq!(v.len(), 42);
42 declare_clippy_lint! {
43 pub NEEDLESS_PASS_BY_VALUE,
45 "functions taking arguments by value, but not consuming them in its body"
48 pub struct NeedlessPassByValue;
50 impl LintPass for NeedlessPassByValue {
51 fn get_lints(&self) -> LintArray {
52 lint_array![NEEDLESS_PASS_BY_VALUE]
57 ($e: expr) => { if let Some(x) = $e { x } else { return; } };
60 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
63 cx: &LateContext<'a, 'tcx>,
75 FnKind::ItemFn(.., abi, _, attrs) => {
80 if a.meta_item_list().is_some() && a.name() == "proc_macro_derive" {
85 FnKind::Method(..) => (),
89 // Exclude non-inherent impls
90 if let Some(NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(node_id)) {
91 if matches!(item.node, ItemImpl(_, _, _, _, Some(_), _, _) |
98 // Allow `Borrow` or functions to be taken by value
99 let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
100 let whitelisted_traits = [
101 need!(cx.tcx.lang_items().fn_trait()),
102 need!(cx.tcx.lang_items().fn_once_trait()),
103 need!(cx.tcx.lang_items().fn_mut_trait()),
104 need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT))
107 let sized_trait = need!(cx.tcx.lang_items().sized_trait());
109 let fn_def_id = cx.tcx.hir.local_def_id(node_id);
111 let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
112 .filter(|p| !p.is_global())
114 if let ty::Predicate::Trait(poly_trait_ref) = pred {
115 if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_regions() {
123 .collect::<Vec<_>>();
125 // Collect moved variables and spans which will need dereferencings from the
127 let MovedVariablesCtxt {
132 let mut ctx = MovedVariablesCtxt::new(cx);
133 let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
134 euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None)
139 let fn_sig = cx.tcx.fn_sig(fn_def_id);
140 let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
142 for (idx, ((input, &ty), arg)) in decl.inputs
144 .zip(fn_sig.inputs())
145 .zip(&body.arguments)
148 // All spans generated from a proc-macro invocation are the same...
149 if span == input.span {
155 if let PatKind::Binding(_, _, name, ..) = arg.pat.node {
156 if name.node.as_str() == "self" {
162 // * Exclude a type that is specifically bounded by `Borrow`.
163 // * Exclude a type whose reference also fulfills its bound.
164 // (e.g. `std::convert::AsRef`, `serde::Serialize`)
165 let (implements_borrow_trait, all_borrowable_trait) = {
168 .filter(|t| t.skip_binder().self_ty() == ty)
169 .collect::<Vec<_>>();
172 preds.iter().any(|t| t.def_id() == borrow_trait),
173 !preds.is_empty() && preds.iter().all(|t| {
176 cx.tcx.mk_imm_ref(&RegionKind::ReErased, ty),
178 &t.skip_binder().input_types().skip(1).collect::<Vec<_>>(),
186 if !ty.is_mutable_pointer();
188 if !whitelisted_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
189 if !implements_borrow_trait;
190 if !all_borrowable_trait;
192 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.node;
193 if !moved_vars.contains(&canonical_id);
195 if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
199 // Dereference suggestion
200 let sugg = |db: &mut DiagnosticBuilder| {
201 if let ty::TypeVariants::TyAdt(def, ..) = ty.sty {
202 if let Some(span) = cx.tcx.hir.span_if_local(def.did) {
203 let param_env = ty::ParamEnv::empty();
204 if param_env.can_type_implement_copy(cx.tcx, ty, span).is_ok() {
205 db.span_help(span, "consider marking this type as Copy");
210 let deref_span = spans_need_deref.get(&canonical_id);
212 if match_type(cx, ty, &paths::VEC);
213 if let Some(clone_spans) =
214 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
215 if let TyPath(QPath::Resolved(_, ref path)) = input.node;
216 if let Some(elem_ty) = path.segments.iter()
217 .find(|seg| seg.name == "Vec")
218 .and_then(|ps| ps.parameters.as_ref())
219 .map(|params| ¶ms.types[0]);
221 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
222 db.span_suggestion(input.span,
223 "consider changing the type to",
226 for (span, suggestion) in clone_spans {
229 &snippet_opt(cx, span)
231 "change the call to".into(),
232 |x| Cow::from(format!("change `{}` to", x)),
238 // cannot be destructured, no need for `*` suggestion
239 assert!(deref_span.is_none());
244 if match_type(cx, ty, &paths::STRING) {
245 if let Some(clone_spans) =
246 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
247 db.span_suggestion(input.span, "consider changing the type to", "&str".to_string());
249 for (span, suggestion) in clone_spans {
252 &snippet_opt(cx, span)
254 "change the call to".into(),
255 |x| Cow::from(format!("change `{}` to", x))
261 assert!(deref_span.is_none());
266 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
268 // Suggests adding `*` to dereference the added reference.
269 if let Some(deref_span) = deref_span {
274 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
276 spans.sort_by_key(|&(span, _)| span);
278 multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
283 NEEDLESS_PASS_BY_VALUE,
285 "this argument is passed by value, but not consumed in the function body",
294 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
295 cx: &'a LateContext<'a, 'tcx>,
296 moved_vars: HashSet<NodeId>,
297 /// Spans which need to be prefixed with `*` for dereferencing the
298 /// suggested additional reference.
299 spans_need_deref: HashMap<NodeId, HashSet<Span>>,
302 impl<'a, 'tcx> MovedVariablesCtxt<'a, 'tcx> {
303 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
306 moved_vars: HashSet::new(),
307 spans_need_deref: HashMap::new(),
311 fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: mc::cmt<'tcx>) {
312 let cmt = unwrap_downcast_or_interior(cmt);
314 if let mc::Categorization::Local(vid) = cmt.cat {
315 self.moved_vars.insert(vid);
319 fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>) {
320 let cmt = unwrap_downcast_or_interior(cmt);
322 if let mc::Categorization::Local(vid) = cmt.cat {
323 let mut id = matched_pat.id;
325 let parent = self.cx.tcx.hir.get_parent_node(id);
332 if let Some(node) = self.cx.tcx.hir.find(id) {
334 map::Node::NodeExpr(e) => {
335 // `match` and `if let`
336 if let ExprMatch(ref c, ..) = e.node {
337 self.spans_need_deref
339 .or_insert_with(HashSet::new)
344 map::Node::NodeStmt(s) => {
347 if let StmtDecl(ref decl, _) = s.node;
348 if let DeclLocal(ref local) = decl.node;
350 self.spans_need_deref
352 .or_insert_with(HashSet::new)
356 .expect("`let` stmt without init aren't caught by match_pat"));
369 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
370 fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
371 if let euv::ConsumeMode::Move(_) = mode {
372 self.move_common(consume_id, consume_span, cmt);
376 fn matched_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) {
377 if let euv::MatchMode::MovingMatch = mode {
378 self.move_common(matched_pat.id, matched_pat.span, cmt);
380 self.non_moving_pat(matched_pat, cmt);
384 fn consume_pat(&mut self, consume_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
385 if let euv::ConsumeMode::Move(_) = mode {
386 self.move_common(consume_pat.id, consume_pat.span, cmt);
390 fn borrow(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, _: euv::LoanCause) {}
392 fn mutate(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: euv::MutateMode) {}
394 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
398 fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt {
400 match cmt.cat.clone() {
401 mc::Categorization::Downcast(c, _) | mc::Categorization::Interior(c, _) => {