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>,
58 if in_macro(cx, span) {
62 if !matches!(kind, FnKind::ItemFn(..)) {
66 // Allows these to be passed by value.
67 let fn_trait = need!(cx.tcx.lang_items.fn_trait());
68 let asref_trait = need!(get_trait_def_id(cx, &paths::ASREF_TRAIT));
69 let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
71 let preds: Vec<ty::Predicate> = {
72 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, node_id);
73 traits::elaborate_predicates(cx.tcx, parameter_env.caller_bounds.clone())
74 .filter(|p| !p.is_global())
78 // Collect moved variables and spans which will need dereferencings from the function body.
79 let MovedVariablesCtxt { moved_vars, spans_need_deref, .. } = {
80 let mut ctx = MovedVariablesCtxt::new(cx);
81 let infcx = cx.tcx.borrowck_fake_infer_ctxt(body.id());
83 let mut v = euv::ExprUseVisitor::new(&mut ctx, &infcx);
89 let fn_def_id = cx.tcx.hir.local_def_id(node_id);
90 let param_env = ty::ParameterEnvironment::for_item(cx.tcx, node_id);
91 let fn_sig = cx.tcx.item_type(fn_def_id).fn_sig();
92 let fn_sig = cx.tcx.liberate_late_bound_regions(param_env.free_id_outlive, &fn_sig);
94 for ((input, ty), arg) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments) {
96 // Determines whether `ty` implements `Borrow<U>` (U != ty) specifically.
97 // This is needed due to the `Borrow<T> for T` blanket impl.
98 let implements_borrow_trait = preds.iter()
99 .filter_map(|pred| if let ty::Predicate::Trait(ref poly_trait_ref) = *pred {
100 Some(poly_trait_ref.skip_binder())
104 .filter(|tpred| tpred.def_id() == borrow_trait && &tpred.self_ty() == ty)
105 .any(|tpred| &tpred.input_types().nth(1).expect("Borrow trait must have an parameter") != ty);
109 !ty.is_mutable_pointer(),
110 !is_copy(cx, ty, node_id),
111 !implements_trait(cx, ty, fn_trait, &[], Some(node_id)),
112 !implements_trait(cx, ty, asref_trait, &[], Some(node_id)),
113 !implements_borrow_trait,
115 let PatKind::Binding(mode, defid, ..) = arg.pat.node,
116 !moved_vars.contains(&defid),
118 // Note: `toplevel_ref_arg` warns if `BindByRef`
120 BindingMode::BindByRef(m) | BindingMode::BindByValue(m) => m,
122 if m == Mutability::MutMutable {
127 let sugg = |db: &mut DiagnosticBuilder| {
128 let deref_span = spans_need_deref.get(&defid);
130 match_type(cx, ty, &paths::VEC),
131 let TyPath(QPath::Resolved(_, ref path)) = input.node,
132 let Some(elem_ty) = path.segments.iter()
133 .find(|seg| &*seg.name.as_str() == "Vec")
134 .map(|ps| ps.parameters.types()[0]),
136 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
137 db.span_suggestion(input.span,
138 &format!("consider changing the type to `{}`", slice_ty),
140 assert!(deref_span.is_none());
141 return; // `Vec` and `String` cannot be destructured - no need for `*` suggestion
144 if match_type(cx, ty, &paths::STRING) {
145 db.span_suggestion(input.span,
146 "consider changing the type to `&str`",
148 assert!(deref_span.is_none());
152 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
154 // Suggests adding `*` to dereference the added reference.
155 if let Some(deref_span) = deref_span {
156 spans.extend(deref_span.iter().cloned()
157 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))));
158 spans.sort_by_key(|&(span, _)| span);
160 multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
163 span_lint_and_then(cx,
164 NEEDLESS_PASS_BY_VALUE,
166 "this argument is passed by value, but not consumed in the function body",
173 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
174 cx: &'a LateContext<'a, 'tcx>,
175 moved_vars: HashSet<DefId>,
176 /// Spans which need to be prefixed with `*` for dereferencing the suggested additional
178 spans_need_deref: HashMap<DefId, HashSet<Span>>,
181 impl<'a, 'tcx: 'a> MovedVariablesCtxt<'a, 'tcx> {
182 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
185 moved_vars: HashSet::new(),
186 spans_need_deref: HashMap::new(),
190 fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: mc::cmt<'tcx>) {
191 let cmt = unwrap_downcast_or_interior(cmt);
194 let mc::Categorization::Local(vid) = cmt.cat,
195 let Some(def_id) = self.cx.tcx.hir.opt_local_def_id(vid),
197 self.moved_vars.insert(def_id);
201 fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>) {
202 let cmt = unwrap_downcast_or_interior(cmt);
205 let mc::Categorization::Local(vid) = cmt.cat,
206 let Some(def_id) = self.cx.tcx.hir.opt_local_def_id(vid),
208 let mut id = matched_pat.id;
210 let parent = self.cx.tcx.hir.get_parent_node(id);
217 if let Some(node) = self.cx.tcx.hir.find(id) {
219 map::Node::NodeExpr(e) => {
220 // `match` and `if let`
221 if let ExprMatch(ref c, ..) = e.node {
222 self.spans_need_deref
224 .or_insert_with(HashSet::new)
229 map::Node::NodeStmt(s) => {
232 let StmtDecl(ref decl, _) = s.node,
233 let DeclLocal(ref local) = decl.node,
235 self.spans_need_deref
237 .or_insert_with(HashSet::new)
241 .expect("`let` stmt without init aren't caught by match_pat"));
253 impl<'a, 'tcx: 'a> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
254 fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
255 if let euv::ConsumeMode::Move(_) = mode {
256 self.move_common(consume_id, consume_span, cmt);
260 fn matched_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) {
261 if let euv::MatchMode::MovingMatch = mode {
262 self.move_common(matched_pat.id, matched_pat.span, cmt);
264 self.non_moving_pat(matched_pat, cmt);
268 fn consume_pat(&mut self, consume_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
269 if let euv::ConsumeMode::Move(_) = mode {
270 self.move_common(consume_pat.id, consume_pat.span, cmt);
285 fn mutate(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: euv::MutateMode) {}
287 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
291 fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt {
293 match cmt.cat.clone() {
294 mc::Categorization::Downcast(c, _) |
295 mc::Categorization::Interior(c, _) => {