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