2 use rustc::hir::intravisit::FnKind;
4 use rustc::ty::{self, RegionKind, TypeFoldable};
6 use rustc::middle::expr_use_visitor as euv;
7 use rustc::middle::mem_categorization as mc;
8 use syntax::ast::NodeId;
10 use syntax::errors::DiagnosticBuilder;
11 use utils::{get_trait_def_id, implements_trait, in_macro, is_copy, is_self, match_type, multispan_sugg, paths,
12 snippet, snippet_opt, span_lint_and_then};
13 use utils::ptr::get_spans;
14 use std::collections::{HashMap, HashSet};
17 /// **What it does:** Checks for functions taking arguments by value, but not
18 /// consuming them in its
21 /// **Why is this bad?** Taking arguments by reference is more flexible and can
23 /// unnecessary allocations.
25 /// **Known problems:** Hopefully none.
29 /// fn foo(v: Vec<i32>) {
30 /// assert_eq!(v.len(), 42);
34 pub NEEDLESS_PASS_BY_VALUE,
36 "functions taking arguments by value, but not consuming them in its body"
39 pub struct NeedlessPassByValue;
41 impl LintPass for NeedlessPassByValue {
42 fn get_lints(&self) -> LintArray {
43 lint_array![NEEDLESS_PASS_BY_VALUE]
48 ($e: expr) => { if let Some(x) = $e { x } else { return; } };
51 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
54 cx: &LateContext<'a, 'tcx>,
66 FnKind::ItemFn(.., attrs) => for a in attrs {
68 a.meta_item_list().is_some(),
69 let Some(name) = a.name(),
70 name == "proc_macro_derive",
78 // Allow `Borrow` or functions to be taken by value
79 let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
81 need!(cx.tcx.lang_items().fn_trait()),
82 need!(cx.tcx.lang_items().fn_once_trait()),
83 need!(cx.tcx.lang_items().fn_mut_trait()),
86 let sized_trait = need!(cx.tcx.lang_items().sized_trait());
88 let fn_def_id = cx.tcx.hir.local_def_id(node_id);
90 let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
91 .filter(|p| !p.is_global())
92 .filter_map(|pred| if let ty::Predicate::Trait(poly_trait_ref) = pred {
93 if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_regions() {
100 .collect::<Vec<_>>();
102 // Collect moved variables and spans which will need dereferencings from the
104 let MovedVariablesCtxt {
109 let mut ctx = MovedVariablesCtxt::new(cx);
110 let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
111 euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables).consume_body(body);
115 let fn_sig = cx.tcx.fn_sig(fn_def_id);
116 let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
118 for (idx, ((input, &ty), arg)) in decl.inputs
120 .zip(fn_sig.inputs())
121 .zip(&body.arguments)
124 // * Exclude a type that is specifically bounded by `Borrow`.
125 // * Exclude a type whose reference also fulfills its bound.
126 // (e.g. `std::convert::AsRef`, `serde::Serialize`)
127 let (implements_borrow_trait, all_borrowable_trait) = {
130 .filter(|t| t.skip_binder().self_ty() == ty)
131 .collect::<Vec<_>>();
134 preds.iter().any(|t| t.def_id() == borrow_trait),
135 !preds.is_empty() && preds.iter().all(|t| {
138 cx.tcx.mk_imm_ref(&RegionKind::ReErased, ty),
140 &t.skip_binder().input_types().skip(1).collect::<Vec<_>>(),
148 !ty.is_mutable_pointer(),
150 !fn_traits.iter().any(|&t| implements_trait(cx, ty, t, &[])),
151 !implements_borrow_trait,
152 !all_borrowable_trait,
154 let PatKind::Binding(mode, canonical_id, ..) = arg.pat.node,
155 !moved_vars.contains(&canonical_id),
157 if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
161 // Dereference suggestion
162 let sugg = |db: &mut DiagnosticBuilder| {
163 let deref_span = spans_need_deref.get(&canonical_id);
165 match_type(cx, ty, &paths::VEC),
166 let Some(clone_spans) =
167 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]),
168 let TyPath(QPath::Resolved(_, ref path)) = input.node,
169 let Some(elem_ty) = path.segments.iter()
170 .find(|seg| seg.name == "Vec")
171 .and_then(|ps| ps.parameters.as_ref())
172 .map(|params| ¶ms.types[0]),
174 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
175 db.span_suggestion(input.span,
176 "consider changing the type to",
179 for (span, suggestion) in clone_spans {
182 &snippet_opt(cx, span)
184 "change the call to".into(),
185 |x| Cow::from(format!("change `{}` to", x)),
191 // cannot be destructured, no need for `*` suggestion
192 assert!(deref_span.is_none());
196 if match_type(cx, ty, &paths::STRING) {
197 if let Some(clone_spans) =
198 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
199 db.span_suggestion(input.span, "consider changing the type to", "&str".to_string());
201 for (span, suggestion) in clone_spans {
204 &snippet_opt(cx, span)
206 "change the call to".into(),
207 |x| Cow::from(format!("change `{}` to", x))
213 assert!(deref_span.is_none());
218 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
220 // Suggests adding `*` to dereference the added reference.
221 if let Some(deref_span) = deref_span {
226 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
228 spans.sort_by_key(|&(span, _)| span);
230 multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
235 NEEDLESS_PASS_BY_VALUE,
237 "this argument is passed by value, but not consumed in the function body",
245 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
246 cx: &'a LateContext<'a, 'tcx>,
247 moved_vars: HashSet<NodeId>,
248 /// Spans which need to be prefixed with `*` for dereferencing the
249 /// suggested additional reference.
250 spans_need_deref: HashMap<NodeId, HashSet<Span>>,
253 impl<'a, 'tcx> MovedVariablesCtxt<'a, 'tcx> {
254 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
257 moved_vars: HashSet::new(),
258 spans_need_deref: HashMap::new(),
262 fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: mc::cmt<'tcx>) {
263 let cmt = unwrap_downcast_or_interior(cmt);
265 if let mc::Categorization::Local(vid) = cmt.cat {
266 self.moved_vars.insert(vid);
270 fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>) {
271 let cmt = unwrap_downcast_or_interior(cmt);
273 if let mc::Categorization::Local(vid) = cmt.cat {
274 let mut id = matched_pat.id;
276 let parent = self.cx.tcx.hir.get_parent_node(id);
283 if let Some(node) = self.cx.tcx.hir.find(id) {
285 map::Node::NodeExpr(e) => {
286 // `match` and `if let`
287 if let ExprMatch(ref c, ..) = e.node {
288 self.spans_need_deref
290 .or_insert_with(HashSet::new)
295 map::Node::NodeStmt(s) => {
298 let StmtDecl(ref decl, _) = s.node,
299 let DeclLocal(ref local) = decl.node,
301 self.spans_need_deref
303 .or_insert_with(HashSet::new)
307 .expect("`let` stmt without init aren't caught by match_pat"));
319 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
320 fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
321 if let euv::ConsumeMode::Move(_) = mode {
322 self.move_common(consume_id, consume_span, cmt);
326 fn matched_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) {
327 if let euv::MatchMode::MovingMatch = mode {
328 self.move_common(matched_pat.id, matched_pat.span, cmt);
330 self.non_moving_pat(matched_pat, cmt);
334 fn consume_pat(&mut self, consume_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
335 if let euv::ConsumeMode::Move(_) = mode {
336 self.move_common(consume_pat.id, consume_pat.span, cmt);
340 fn borrow(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, _: euv::LoanCause) {}
342 fn mutate(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: euv::MutateMode) {}
344 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
348 fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt {
350 match cmt.cat.clone() {
351 mc::Categorization::Downcast(c, _) | mc::Categorization::Interior(c, _) => {