]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Add missing diagnostic item Symbols
[rust.git] / clippy_lints / src / needless_pass_by_value.rs
1 use crate::utils::ptr::get_spans;
2 use crate::utils::{
3     get_trait_def_id, implements_trait, is_copy, is_self, is_type_diagnostic_item, multispan_sugg, paths, snippet,
4     snippet_opt, span_lint_and_then,
5 };
6 use if_chain::if_chain;
7 use rustc_ast::ast::Attribute;
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_errors::{Applicability, DiagnosticBuilder};
10 use rustc_hir::intravisit::FnKind;
11 use rustc_hir::{BindingAnnotation, Body, FnDecl, GenericArg, HirId, Impl, ItemKind, Node, PatKind, QPath, TyKind};
12 use rustc_infer::infer::TyCtxtInferExt;
13 use rustc_lint::{LateContext, LateLintPass};
14 use rustc_middle::ty::{self, TypeFoldable};
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 use rustc_span::symbol::kw;
17 use rustc_span::{sym, Span};
18 use rustc_target::spec::abi::Abi;
19 use rustc_trait_selection::traits;
20 use rustc_trait_selection::traits::misc::can_type_implement_copy;
21 use rustc_typeck::expr_use_visitor as euv;
22 use std::borrow::Cow;
23
24 declare_clippy_lint! {
25     /// **What it does:** Checks for functions taking arguments by value, but not
26     /// consuming them in its
27     /// body.
28     ///
29     /// **Why is this bad?** Taking arguments by reference is more flexible and can
30     /// sometimes avoid
31     /// unnecessary allocations.
32     ///
33     /// **Known problems:**
34     /// * This lint suggests taking an argument by reference,
35     /// however sometimes it is better to let users decide the argument type
36     /// (by using `Borrow` trait, for example), depending on how the function is used.
37     ///
38     /// **Example:**
39     /// ```rust
40     /// fn foo(v: Vec<i32>) {
41     ///     assert_eq!(v.len(), 42);
42     /// }
43     /// ```
44     /// should be
45     /// ```rust
46     /// fn foo(v: &[i32]) {
47     ///     assert_eq!(v.len(), 42);
48     /// }
49     /// ```
50     pub NEEDLESS_PASS_BY_VALUE,
51     pedantic,
52     "functions taking arguments by value, but not consuming them in its body"
53 }
54
55 declare_lint_pass!(NeedlessPassByValue => [NEEDLESS_PASS_BY_VALUE]);
56
57 macro_rules! need {
58     ($e: expr) => {
59         if let Some(x) = $e {
60             x
61         } else {
62             return;
63         }
64     };
65 }
66
67 impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue {
68     #[allow(clippy::too_many_lines)]
69     fn check_fn(
70         &mut self,
71         cx: &LateContext<'tcx>,
72         kind: FnKind<'tcx>,
73         decl: &'tcx FnDecl<'_>,
74         body: &'tcx Body<'_>,
75         span: Span,
76         hir_id: HirId,
77     ) {
78         if span.from_expansion() {
79             return;
80         }
81
82         match kind {
83             FnKind::ItemFn(.., header, _, attrs) => {
84                 if header.abi != Abi::Rust || requires_exact_signature(attrs) {
85                     return;
86                 }
87             },
88             FnKind::Method(..) => (),
89             FnKind::Closure(..) => return,
90         }
91
92         // Exclude non-inherent impls
93         if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
94             if matches!(
95                 item.kind,
96                 ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..)
97             ) {
98                 return;
99             }
100         }
101
102         // Allow `Borrow` or functions to be taken by value
103         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
104         let allowed_traits = [
105             need!(cx.tcx.lang_items().fn_trait()),
106             need!(cx.tcx.lang_items().fn_once_trait()),
107             need!(cx.tcx.lang_items().fn_mut_trait()),
108             need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT)),
109         ];
110
111         let sized_trait = need!(cx.tcx.lang_items().sized_trait());
112
113         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
114
115         let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds().iter())
116             .filter(|p| !p.is_global())
117             .filter_map(|obligation| {
118                 // Note that we do not want to deal with qualified predicates here.
119                 match obligation.predicate.kind().no_bound_vars() {
120                     Some(ty::PredicateKind::Trait(pred, _)) if pred.def_id() != sized_trait => Some(pred),
121                     _ => None,
122                 }
123             })
124             .collect::<Vec<_>>();
125
126         // Collect moved variables and spans which will need dereferencings from the
127         // function body.
128         let MovedVariablesCtxt {
129             moved_vars,
130             spans_need_deref,
131             ..
132         } = {
133             let mut ctx = MovedVariablesCtxt::default();
134             cx.tcx.infer_ctxt().enter(|infcx| {
135                 euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.typeck_results())
136                     .consume_body(body);
137             });
138             ctx
139         };
140
141         let fn_sig = cx.tcx.fn_sig(fn_def_id);
142         let fn_sig = cx.tcx.erase_late_bound_regions(fn_sig);
143
144         for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(body.params).enumerate() {
145             // All spans generated from a proc-macro invocation are the same...
146             if span == input.span {
147                 return;
148             }
149
150             // Ignore `self`s.
151             if idx == 0 {
152                 if let PatKind::Binding(.., ident, _) = arg.pat.kind {
153                     if ident.name == kw::SelfLower {
154                         continue;
155                     }
156                 }
157             }
158
159             //
160             // * Exclude a type that is specifically bounded by `Borrow`.
161             // * Exclude a type whose reference also fulfills its bound. (e.g., `std::convert::AsRef`,
162             //   `serde::Serialize`)
163             let (implements_borrow_trait, all_borrowable_trait) = {
164                 let preds = preds.iter().filter(|t| t.self_ty() == ty).collect::<Vec<_>>();
165
166                 (
167                     preds.iter().any(|t| t.def_id() == borrow_trait),
168                     !preds.is_empty() && {
169                         let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty);
170                         preds.iter().all(|t| {
171                             let ty_params = t.trait_ref.substs.iter().skip(1).collect::<Vec<_>>();
172                             implements_trait(cx, ty_empty_region, t.def_id(), &ty_params)
173                         })
174                     },
175                 )
176             };
177
178             if_chain! {
179                 if !is_self(arg);
180                 if !ty.is_mutable_ptr();
181                 if !is_copy(cx, ty);
182                 if !allowed_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
183                 if !implements_borrow_trait;
184                 if !all_borrowable_trait;
185
186                 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.kind;
187                 if !moved_vars.contains(&canonical_id);
188                 then {
189                     if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
190                         continue;
191                     }
192
193                     // Dereference suggestion
194                     let sugg = |diag: &mut DiagnosticBuilder<'_>| {
195                         if let ty::Adt(def, ..) = ty.kind() {
196                             if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
197                                 if can_type_implement_copy(cx.tcx, cx.param_env, ty).is_ok() {
198                                     diag.span_help(span, "consider marking this type as `Copy`");
199                                 }
200                             }
201                         }
202
203                         let deref_span = spans_need_deref.get(&canonical_id);
204                         if_chain! {
205                             if is_type_diagnostic_item(cx, ty, sym::vec_type);
206                             if let Some(clone_spans) =
207                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
208                             if let TyKind::Path(QPath::Resolved(_, ref path)) = input.kind;
209                             if let Some(elem_ty) = path.segments.iter()
210                                 .find(|seg| seg.ident.name == sym::Vec)
211                                 .and_then(|ps| ps.args.as_ref())
212                                 .map(|params| params.args.iter().find_map(|arg| match arg {
213                                     GenericArg::Type(ty) => Some(ty),
214                                     _ => None,
215                                 }).unwrap());
216                             then {
217                                 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
218                                 diag.span_suggestion(
219                                     input.span,
220                                     "consider changing the type to",
221                                     slice_ty,
222                                     Applicability::Unspecified,
223                                 );
224
225                                 for (span, suggestion) in clone_spans {
226                                     diag.span_suggestion(
227                                         span,
228                                         &snippet_opt(cx, span)
229                                             .map_or(
230                                                 "change the call to".into(),
231                                                 |x| Cow::from(format!("change `{}` to", x)),
232                                             ),
233                                         suggestion.into(),
234                                         Applicability::Unspecified,
235                                     );
236                                 }
237
238                                 // cannot be destructured, no need for `*` suggestion
239                                 assert!(deref_span.is_none());
240                                 return;
241                             }
242                         }
243
244                         if is_type_diagnostic_item(cx, ty, sym::string_type) {
245                             if let Some(clone_spans) =
246                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
247                                 diag.span_suggestion(
248                                     input.span,
249                                     "consider changing the type to",
250                                     "&str".to_string(),
251                                     Applicability::Unspecified,
252                                 );
253
254                                 for (span, suggestion) in clone_spans {
255                                     diag.span_suggestion(
256                                         span,
257                                         &snippet_opt(cx, span)
258                                             .map_or(
259                                                 "change the call to".into(),
260                                                 |x| Cow::from(format!("change `{}` to", x))
261                                             ),
262                                         suggestion.into(),
263                                         Applicability::Unspecified,
264                                     );
265                                 }
266
267                                 assert!(deref_span.is_none());
268                                 return;
269                             }
270                         }
271
272                         let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
273
274                         // Suggests adding `*` to dereference the added reference.
275                         if let Some(deref_span) = deref_span {
276                             spans.extend(
277                                 deref_span
278                                     .iter()
279                                     .cloned()
280                                     .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
281                             );
282                             spans.sort_by_key(|&(span, _)| span);
283                         }
284                         multispan_sugg(diag, "consider taking a reference instead", spans);
285                     };
286
287                     span_lint_and_then(
288                         cx,
289                         NEEDLESS_PASS_BY_VALUE,
290                         input.span,
291                         "this argument is passed by value, but not consumed in the function body",
292                         sugg,
293                     );
294                 }
295             }
296         }
297     }
298 }
299
300 /// Functions marked with these attributes must have the exact signature.
301 fn requires_exact_signature(attrs: &[Attribute]) -> bool {
302     attrs.iter().any(|attr| {
303         [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
304             .iter()
305             .any(|&allow| attr.has_name(allow))
306     })
307 }
308
309 #[derive(Default)]
310 struct MovedVariablesCtxt {
311     moved_vars: FxHashSet<HirId>,
312     /// Spans which need to be prefixed with `*` for dereferencing the
313     /// suggested additional reference.
314     spans_need_deref: FxHashMap<HirId, FxHashSet<Span>>,
315 }
316
317 impl MovedVariablesCtxt {
318     fn move_common(&mut self, cmt: &euv::PlaceWithHirId<'_>) {
319         if let euv::PlaceBase::Local(vid) = cmt.place.base {
320             self.moved_vars.insert(vid);
321         }
322     }
323 }
324
325 impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt {
326     fn consume(&mut self, cmt: &euv::PlaceWithHirId<'tcx>, _: HirId, mode: euv::ConsumeMode) {
327         if let euv::ConsumeMode::Move = mode {
328             self.move_common(cmt);
329         }
330     }
331
332     fn borrow(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {}
333
334     fn mutate(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId) {}
335 }