]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Auto merge of #74821 - oli-obk:const_eval_read_uninit_fast_path, r=wesleywiser
[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, 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::Span;
17 use rustc_target::spec::abi::Abi;
18 use rustc_trait_selection::traits;
19 use rustc_trait_selection::traits::misc::can_type_implement_copy;
20 use rustc_typeck::expr_use_visitor as euv;
21 use std::borrow::Cow;
22
23 declare_clippy_lint! {
24     /// **What it does:** Checks for functions taking arguments by value, but not
25     /// consuming them in its
26     /// body.
27     ///
28     /// **Why is this bad?** Taking arguments by reference is more flexible and can
29     /// sometimes avoid
30     /// unnecessary allocations.
31     ///
32     /// **Known problems:**
33     /// * This lint suggests taking an argument by reference,
34     /// however sometimes it is better to let users decide the argument type
35     /// (by using `Borrow` trait, for example), depending on how the function is used.
36     ///
37     /// **Example:**
38     /// ```rust
39     /// fn foo(v: Vec<i32>) {
40     ///     assert_eq!(v.len(), 42);
41     /// }
42     /// ```
43     ///
44     /// ```rust
45     /// // should be
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!(item.kind, ItemKind::Impl{ of_trait: Some(_), .. } |
95                 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                 if let ty::PredicateKind::Atom(ty::PredicateAtom::Trait(pred, _)) = obligation.predicate.kind() {
119                     if pred.def_id() == sized_trait {
120                         return None;
121                     }
122                     Some(pred)
123                 } else {
124                     None
125                 }
126             })
127             .collect::<Vec<_>>();
128
129         // Collect moved variables and spans which will need dereferencings from the
130         // function body.
131         let MovedVariablesCtxt {
132             moved_vars,
133             spans_need_deref,
134             ..
135         } = {
136             let mut ctx = MovedVariablesCtxt::default();
137             cx.tcx.infer_ctxt().enter(|infcx| {
138                 euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.typeck_results())
139                     .consume_body(body);
140             });
141             ctx
142         };
143
144         let fn_sig = cx.tcx.fn_sig(fn_def_id);
145         let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
146
147         for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(body.params).enumerate() {
148             // All spans generated from a proc-macro invocation are the same...
149             if span == input.span {
150                 return;
151             }
152
153             // Ignore `self`s.
154             if idx == 0 {
155                 if let PatKind::Binding(.., ident, _) = arg.pat.kind {
156                     if ident.as_str() == "self" {
157                         continue;
158                     }
159                 }
160             }
161
162             // * Exclude a type that is specifically bounded by `Borrow`.
163             // * Exclude a type whose reference also fulfills its bound. (e.g., `std::convert::AsRef`,
164             //   `serde::Serialize`)
165             let (implements_borrow_trait, all_borrowable_trait) = {
166                 let preds = preds
167                     .iter()
168                     .filter(|t| t.self_ty() == ty)
169                     .collect::<Vec<_>>();
170
171                 (
172                     preds.iter().any(|t| t.def_id() == borrow_trait),
173                     !preds.is_empty() && {
174                         let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty);
175                         preds.iter().all(|t| {
176                             let ty_params = t
177                                 .trait_ref
178                                 .substs
179                                 .iter()
180                                 .skip(1)
181                                 .collect::<Vec<_>>();
182                             implements_trait(cx, ty_empty_region, t.def_id(), &ty_params)
183                         })
184                     },
185                 )
186             };
187
188             if_chain! {
189                 if !is_self(arg);
190                 if !ty.is_mutable_ptr();
191                 if !is_copy(cx, ty);
192                 if !allowed_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
193                 if !implements_borrow_trait;
194                 if !all_borrowable_trait;
195
196                 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.kind;
197                 if !moved_vars.contains(&canonical_id);
198                 then {
199                     if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
200                         continue;
201                     }
202
203                     // Dereference suggestion
204                     let sugg = |diag: &mut DiagnosticBuilder<'_>| {
205                         if let ty::Adt(def, ..) = ty.kind {
206                             if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
207                                 if can_type_implement_copy(cx.tcx, cx.param_env, ty).is_ok() {
208                                     diag.span_help(span, "consider marking this type as `Copy`");
209                                 }
210                             }
211                         }
212
213                         let deref_span = spans_need_deref.get(&canonical_id);
214                         if_chain! {
215                             if is_type_diagnostic_item(cx, ty, sym!(vec_type));
216                             if let Some(clone_spans) =
217                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
218                             if let TyKind::Path(QPath::Resolved(_, ref path)) = input.kind;
219                             if let Some(elem_ty) = path.segments.iter()
220                                 .find(|seg| seg.ident.name == sym!(Vec))
221                                 .and_then(|ps| ps.args.as_ref())
222                                 .map(|params| params.args.iter().find_map(|arg| match arg {
223                                     GenericArg::Type(ty) => Some(ty),
224                                     _ => None,
225                                 }).unwrap());
226                             then {
227                                 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
228                                 diag.span_suggestion(
229                                     input.span,
230                                     "consider changing the type to",
231                                     slice_ty,
232                                     Applicability::Unspecified,
233                                 );
234
235                                 for (span, suggestion) in clone_spans {
236                                     diag.span_suggestion(
237                                         span,
238                                         &snippet_opt(cx, span)
239                                             .map_or(
240                                                 "change the call to".into(),
241                                                 |x| Cow::from(format!("change `{}` to", x)),
242                                             ),
243                                         suggestion.into(),
244                                         Applicability::Unspecified,
245                                     );
246                                 }
247
248                                 // cannot be destructured, no need for `*` suggestion
249                                 assert!(deref_span.is_none());
250                                 return;
251                             }
252                         }
253
254                         if is_type_diagnostic_item(cx, ty, sym!(string_type)) {
255                             if let Some(clone_spans) =
256                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
257                                 diag.span_suggestion(
258                                     input.span,
259                                     "consider changing the type to",
260                                     "&str".to_string(),
261                                     Applicability::Unspecified,
262                                 );
263
264                                 for (span, suggestion) in clone_spans {
265                                     diag.span_suggestion(
266                                         span,
267                                         &snippet_opt(cx, span)
268                                             .map_or(
269                                                 "change the call to".into(),
270                                                 |x| Cow::from(format!("change `{}` to", x))
271                                             ),
272                                         suggestion.into(),
273                                         Applicability::Unspecified,
274                                     );
275                                 }
276
277                                 assert!(deref_span.is_none());
278                                 return;
279                             }
280                         }
281
282                         let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
283
284                         // Suggests adding `*` to dereference the added reference.
285                         if let Some(deref_span) = deref_span {
286                             spans.extend(
287                                 deref_span
288                                     .iter()
289                                     .cloned()
290                                     .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
291                             );
292                             spans.sort_by_key(|&(span, _)| span);
293                         }
294                         multispan_sugg(diag, "consider taking a reference instead", spans);
295                     };
296
297                     span_lint_and_then(
298                         cx,
299                         NEEDLESS_PASS_BY_VALUE,
300                         input.span,
301                         "this argument is passed by value, but not consumed in the function body",
302                         sugg,
303                     );
304                 }
305             }
306         }
307     }
308 }
309
310 /// Functions marked with these attributes must have the exact signature.
311 fn requires_exact_signature(attrs: &[Attribute]) -> bool {
312     attrs.iter().any(|attr| {
313         [sym!(proc_macro), sym!(proc_macro_attribute), sym!(proc_macro_derive)]
314             .iter()
315             .any(|&allow| attr.has_name(allow))
316     })
317 }
318
319 #[derive(Default)]
320 struct MovedVariablesCtxt {
321     moved_vars: FxHashSet<HirId>,
322     /// Spans which need to be prefixed with `*` for dereferencing the
323     /// suggested additional reference.
324     spans_need_deref: FxHashMap<HirId, FxHashSet<Span>>,
325 }
326
327 impl MovedVariablesCtxt {
328     fn move_common(&mut self, cmt: &euv::PlaceWithHirId<'_>) {
329         if let euv::PlaceBase::Local(vid) = cmt.place.base {
330             self.moved_vars.insert(vid);
331         }
332     }
333 }
334
335 impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt {
336     fn consume(&mut self, cmt: &euv::PlaceWithHirId<'tcx>, mode: euv::ConsumeMode) {
337         if let euv::ConsumeMode::Move = mode {
338             self.move_common(cmt);
339         }
340     }
341
342     fn borrow(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: ty::BorrowKind) {}
343
344     fn mutate(&mut self, _: &euv::PlaceWithHirId<'tcx>) {}
345 }