2 use rustc::hir::intravisit::FnKind;
3 use rustc::hir::def_id::DefId;
5 use rustc::ty::{self, TypeFoldable};
7 use rustc::middle::expr_use_visitor as euv;
8 use rustc::middle::mem_categorization as mc;
9 use syntax::ast::NodeId;
11 use syntax::errors::DiagnosticBuilder;
12 use utils::{get_trait_def_id, implements_trait, in_macro, is_copy, is_self, match_type, multispan_sugg, paths,
13 snippet, span_lint_and_then};
14 use std::collections::{HashMap, HashSet};
16 /// **What it does:** Checks for functions taking arguments by value, but not
17 /// consuming them in its
20 /// **Why is this bad?** Taking arguments by reference is more flexible and can
22 /// unnecessary allocations.
24 /// **Known problems:** Hopefully none.
28 /// fn foo(v: Vec<i32>) {
29 /// assert_eq!(v.len(), 42);
33 pub NEEDLESS_PASS_BY_VALUE,
35 "functions taking arguments by value, but not consuming them in its body"
38 pub struct NeedlessPassByValue;
40 impl LintPass for NeedlessPassByValue {
41 fn get_lints(&self) -> LintArray {
42 lint_array![NEEDLESS_PASS_BY_VALUE]
47 ($e: expr) => { if let Some(x) = $e { x } else { return; } };
50 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
53 cx: &LateContext<'a, 'tcx>,
65 FnKind::ItemFn(.., attrs) => for a in attrs {
67 a.meta_item_list().is_some(),
68 let Some(name) = a.name(),
69 name == "proc_macro_derive",
77 // Allows these to be passed by value.
78 let fn_trait = need!(cx.tcx.lang_items.fn_trait());
79 let asref_trait = need!(get_trait_def_id(cx, &paths::ASREF_TRAIT));
80 let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
82 let fn_def_id = cx.tcx.hir.local_def_id(node_id);
84 let preds: Vec<ty::Predicate> = {
85 traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
86 .filter(|p| !p.is_global())
90 // Collect moved variables and spans which will need dereferencings from the
92 let MovedVariablesCtxt {
97 let mut ctx = MovedVariablesCtxt::new(cx);
98 let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
99 euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables).consume_body(body);
103 let fn_sig = cx.tcx.fn_sig(fn_def_id);
104 let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
106 for ((input, &ty), arg) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments) {
107 // Determines whether `ty` implements `Borrow<U>` (U != ty) specifically.
108 // This is needed due to the `Borrow<T> for T` blanket impl.
109 let implements_borrow_trait = preds
111 .filter_map(|pred| if let ty::Predicate::Trait(ref poly_trait_ref) = *pred {
112 Some(poly_trait_ref.skip_binder())
116 .filter(|tpred| tpred.def_id() == borrow_trait && tpred.self_ty() == ty)
121 .expect("Borrow trait must have an parameter") != ty
126 !ty.is_mutable_pointer(),
128 !implements_trait(cx, ty, fn_trait, &[]),
129 !implements_trait(cx, ty, asref_trait, &[]),
130 !implements_borrow_trait,
132 let PatKind::Binding(mode, defid, ..) = arg.pat.node,
133 !moved_vars.contains(&defid),
135 // Note: `toplevel_ref_arg` warns if `BindByRef`
136 if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
141 let sugg = |db: &mut DiagnosticBuilder| {
142 let deref_span = spans_need_deref.get(&defid);
144 match_type(cx, ty, &paths::VEC),
145 let TyPath(QPath::Resolved(_, ref path)) = input.node,
146 let Some(elem_ty) = path.segments.iter()
147 .find(|seg| seg.name == "Vec")
148 .map(|ps| &ps.parameters.types[0]),
150 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
151 db.span_suggestion(input.span,
152 "consider changing the type to",
154 assert!(deref_span.is_none());
155 return; // `Vec` and `String` cannot be destructured - no need for `*` suggestion
158 if match_type(cx, ty, &paths::STRING) {
159 db.span_suggestion(input.span,
160 "consider changing the type to",
162 assert!(deref_span.is_none());
166 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
168 // Suggests adding `*` to dereference the added reference.
169 if let Some(deref_span) = deref_span {
170 spans.extend(deref_span.iter().cloned()
171 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))));
172 spans.sort_by_key(|&(span, _)| span);
174 multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
177 span_lint_and_then(cx,
178 NEEDLESS_PASS_BY_VALUE,
180 "this argument is passed by value, but not consumed in the function body",
187 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
188 cx: &'a LateContext<'a, 'tcx>,
189 moved_vars: HashSet<DefId>,
190 /// Spans which need to be prefixed with `*` for dereferencing the
191 /// suggested additional
193 spans_need_deref: HashMap<DefId, HashSet<Span>>,
196 impl<'a, 'tcx> MovedVariablesCtxt<'a, 'tcx> {
197 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
200 moved_vars: HashSet::new(),
201 spans_need_deref: HashMap::new(),
205 fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: mc::cmt<'tcx>) {
206 let cmt = unwrap_downcast_or_interior(cmt);
209 let mc::Categorization::Local(vid) = cmt.cat,
210 let Some(def_id) = self.cx.tcx.hir.opt_local_def_id(vid),
212 self.moved_vars.insert(def_id);
216 fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>) {
217 let cmt = unwrap_downcast_or_interior(cmt);
220 let mc::Categorization::Local(vid) = cmt.cat,
221 let Some(def_id) = self.cx.tcx.hir.opt_local_def_id(vid),
223 let mut id = matched_pat.id;
225 let parent = self.cx.tcx.hir.get_parent_node(id);
232 if let Some(node) = self.cx.tcx.hir.find(id) {
234 map::Node::NodeExpr(e) => {
235 // `match` and `if let`
236 if let ExprMatch(ref c, ..) = e.node {
237 self.spans_need_deref
239 .or_insert_with(HashSet::new)
244 map::Node::NodeStmt(s) => {
247 let StmtDecl(ref decl, _) = s.node,
248 let DeclLocal(ref local) = decl.node,
250 self.spans_need_deref
252 .or_insert_with(HashSet::new)
256 .expect("`let` stmt without init aren't caught by match_pat"));
268 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
269 fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
270 if let euv::ConsumeMode::Move(_) = mode {
271 self.move_common(consume_id, consume_span, cmt);
275 fn matched_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) {
276 if let euv::MatchMode::MovingMatch = mode {
277 self.move_common(matched_pat.id, matched_pat.span, cmt);
279 self.non_moving_pat(matched_pat, cmt);
283 fn consume_pat(&mut self, consume_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
284 if let euv::ConsumeMode::Move(_) = mode {
285 self.move_common(consume_pat.id, consume_pat.span, cmt);
289 fn borrow(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, _: euv::LoanCause) {}
291 fn mutate(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: euv::MutateMode) {}
293 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
297 fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt {
299 match cmt.cat.clone() {
300 mc::Categorization::Downcast(c, _) | mc::Categorization::Interior(c, _) => {