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::{in_macro, is_self, is_copy, implements_trait, get_trait_def_id, match_type, snippet, span_lint_and_then,
13 multispan_sugg, paths};
14 use std::collections::{HashSet, HashMap};
16 /// **What it does:** Checks for functions taking arguments by value, but not consuming them in its
19 /// **Why is this bad?** Taking arguments by reference is more flexible and can sometimes avoid
20 /// unnecessary allocations.
22 /// **Known problems:** Hopefully none.
26 /// fn foo(v: Vec<i32>) {
27 /// assert_eq!(v.len(), 42);
31 pub NEEDLESS_PASS_BY_VALUE,
33 "functions taking arguments by value, but not consuming them in its body"
36 pub struct NeedlessPassByValue;
38 impl LintPass for NeedlessPassByValue {
39 fn get_lints(&self) -> LintArray {
40 lint_array![NEEDLESS_PASS_BY_VALUE]
45 ($e: expr) => { if let Some(x) = $e { x } else { return; } };
48 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
51 cx: &LateContext<'a, 'tcx>,
63 FnKind::ItemFn(.., attrs) => {
66 a.meta_item_list().is_some(),
67 let Some(name) = a.name(),
68 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 let parameter_env = cx.tcx.param_env(fn_def_id);
86 traits::elaborate_predicates(cx.tcx, parameter_env.caller_bounds.to_vec())
87 .filter(|p| !p.is_global())
91 // Collect moved variables and spans which will need dereferencings from the function body.
92 let MovedVariablesCtxt { moved_vars, spans_need_deref, .. } = {
93 let mut ctx = MovedVariablesCtxt::new(cx);
94 let infcx = cx.tcx.borrowck_fake_infer_ctxt(body.id());
95 let region_maps = &cx.tcx.region_maps(fn_def_id);
97 let mut v = euv::ExprUseVisitor::new(&mut ctx, region_maps, &infcx);
103 let fn_sig = cx.tcx.type_of(fn_def_id).fn_sig();
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) {
108 // Determines whether `ty` implements `Borrow<U>` (U != ty) specifically.
109 // This is needed due to the `Borrow<T> for T` blanket impl.
110 let implements_borrow_trait = preds.iter()
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)
117 .any(|tpred| tpred.input_types().nth(1).expect("Borrow trait must have an parameter") != ty);
121 !ty.is_mutable_pointer(),
122 !is_copy(cx, ty, fn_def_id),
123 !implements_trait(cx, ty, fn_trait, &[], Some(node_id)),
124 !implements_trait(cx, ty, asref_trait, &[], Some(node_id)),
125 !implements_borrow_trait,
127 let PatKind::Binding(mode, defid, ..) = arg.pat.node,
128 !moved_vars.contains(&defid),
130 // Note: `toplevel_ref_arg` warns if `BindByRef`
132 BindingMode::BindByRef(m) | BindingMode::BindByValue(m) => m,
134 if m == Mutability::MutMutable {
139 let sugg = |db: &mut DiagnosticBuilder| {
140 let deref_span = spans_need_deref.get(&defid);
142 match_type(cx, ty, &paths::VEC),
143 let TyPath(QPath::Resolved(_, ref path)) = input.node,
144 let Some(elem_ty) = path.segments.iter()
145 .find(|seg| seg.name == "Vec")
146 .map(|ps| ps.parameters.types()[0]),
148 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
149 db.span_suggestion(input.span,
150 "consider changing the type to",
152 assert!(deref_span.is_none());
153 return; // `Vec` and `String` cannot be destructured - no need for `*` suggestion
156 if match_type(cx, ty, &paths::STRING) {
157 db.span_suggestion(input.span,
158 "consider changing the type to",
160 assert!(deref_span.is_none());
164 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
166 // Suggests adding `*` to dereference the added reference.
167 if let Some(deref_span) = deref_span {
168 spans.extend(deref_span.iter().cloned()
169 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))));
170 spans.sort_by_key(|&(span, _)| span);
172 multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
175 span_lint_and_then(cx,
176 NEEDLESS_PASS_BY_VALUE,
178 "this argument is passed by value, but not consumed in the function body",
185 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
186 cx: &'a LateContext<'a, 'tcx>,
187 moved_vars: HashSet<DefId>,
188 /// Spans which need to be prefixed with `*` for dereferencing the suggested additional
190 spans_need_deref: HashMap<DefId, HashSet<Span>>,
193 impl<'a, 'tcx: 'a> MovedVariablesCtxt<'a, 'tcx> {
194 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
197 moved_vars: HashSet::new(),
198 spans_need_deref: HashMap::new(),
202 fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: mc::cmt<'tcx>) {
203 let cmt = unwrap_downcast_or_interior(cmt);
206 let mc::Categorization::Local(vid) = cmt.cat,
207 let Some(def_id) = self.cx.tcx.hir.opt_local_def_id(vid),
209 self.moved_vars.insert(def_id);
213 fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>) {
214 let cmt = unwrap_downcast_or_interior(cmt);
217 let mc::Categorization::Local(vid) = cmt.cat,
218 let Some(def_id) = self.cx.tcx.hir.opt_local_def_id(vid),
220 let mut id = matched_pat.id;
222 let parent = self.cx.tcx.hir.get_parent_node(id);
229 if let Some(node) = self.cx.tcx.hir.find(id) {
231 map::Node::NodeExpr(e) => {
232 // `match` and `if let`
233 if let ExprMatch(ref c, ..) = e.node {
234 self.spans_need_deref
236 .or_insert_with(HashSet::new)
241 map::Node::NodeStmt(s) => {
244 let StmtDecl(ref decl, _) = s.node,
245 let DeclLocal(ref local) = decl.node,
247 self.spans_need_deref
249 .or_insert_with(HashSet::new)
253 .expect("`let` stmt without init aren't caught by match_pat"));
265 impl<'a, 'tcx: 'a> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
266 fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
267 if let euv::ConsumeMode::Move(_) = mode {
268 self.move_common(consume_id, consume_span, cmt);
272 fn matched_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) {
273 if let euv::MatchMode::MovingMatch = mode {
274 self.move_common(matched_pat.id, matched_pat.span, cmt);
276 self.non_moving_pat(matched_pat, cmt);
280 fn consume_pat(&mut self, consume_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
281 if let euv::ConsumeMode::Move(_) = mode {
282 self.move_common(consume_pat.id, consume_pat.span, cmt);
286 fn borrow(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, _: euv::LoanCause) {}
288 fn mutate(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: euv::MutateMode) {}
290 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
294 fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt {
296 match cmt.cat.clone() {
297 mc::Categorization::Downcast(c, _) |
298 mc::Categorization::Interior(c, _) => {