]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Auto merge of #78779 - LeSeulArtichaut:ty-visitor-return, r=oli-obk
[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::{sym, 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     /// should be
44     /// ```rust
45     /// fn foo(v: &[i32]) {
46     ///     assert_eq!(v.len(), 42);
47     /// }
48     /// ```
49     pub NEEDLESS_PASS_BY_VALUE,
50     pedantic,
51     "functions taking arguments by value, but not consuming them in its body"
52 }
53
54 declare_lint_pass!(NeedlessPassByValue => [NEEDLESS_PASS_BY_VALUE]);
55
56 macro_rules! need {
57     ($e: expr) => {
58         if let Some(x) = $e {
59             x
60         } else {
61             return;
62         }
63     };
64 }
65
66 impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue {
67     #[allow(clippy::too_many_lines)]
68     fn check_fn(
69         &mut self,
70         cx: &LateContext<'tcx>,
71         kind: FnKind<'tcx>,
72         decl: &'tcx FnDecl<'_>,
73         body: &'tcx Body<'_>,
74         span: Span,
75         hir_id: HirId,
76     ) {
77         if span.from_expansion() {
78             return;
79         }
80
81         match kind {
82             FnKind::ItemFn(.., header, _, attrs) => {
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!(item.kind, ItemKind::Impl{ of_trait: Some(_), .. } |
94                 ItemKind::Trait(..))
95             {
96                 return;
97             }
98         }
99
100         // Allow `Borrow` or functions to be taken by value
101         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
102         let allowed_traits = [
103             need!(cx.tcx.lang_items().fn_trait()),
104             need!(cx.tcx.lang_items().fn_once_trait()),
105             need!(cx.tcx.lang_items().fn_mut_trait()),
106             need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT)),
107         ];
108
109         let sized_trait = need!(cx.tcx.lang_items().sized_trait());
110
111         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
112
113         let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds().iter())
114             .filter(|p| !p.is_global())
115             .filter_map(|obligation| {
116                 // Note that we do not want to deal with qualified predicates here.
117                 if let ty::PredicateKind::Atom(ty::PredicateAtom::Trait(pred, _)) = obligation.predicate.kind() {
118                     if pred.def_id() == sized_trait {
119                         return None;
120                     }
121                     Some(pred)
122                 } else {
123                     None
124                 }
125             })
126             .collect::<Vec<_>>();
127
128         // Collect moved variables and spans which will need dereferencings from the
129         // function body.
130         let MovedVariablesCtxt {
131             moved_vars,
132             spans_need_deref,
133             ..
134         } = {
135             let mut ctx = MovedVariablesCtxt::default();
136             cx.tcx.infer_ctxt().enter(|infcx| {
137                 euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.typeck_results())
138                     .consume_body(body);
139             });
140             ctx
141         };
142
143         let fn_sig = cx.tcx.fn_sig(fn_def_id);
144         let fn_sig = cx.tcx.erase_late_bound_regions(fn_sig);
145
146         for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(body.params).enumerate() {
147             // All spans generated from a proc-macro invocation are the same...
148             if span == input.span {
149                 return;
150             }
151
152             // Ignore `self`s.
153             if idx == 0 {
154                 if let PatKind::Binding(.., ident, _) = arg.pat.kind {
155                     if ident.as_str() == "self" {
156                         continue;
157                     }
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.iter().filter(|t| t.self_ty() == ty).collect::<Vec<_>>();
167
168                 (
169                     preds.iter().any(|t| t.def_id() == borrow_trait),
170                     !preds.is_empty() && {
171                         let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty);
172                         preds.iter().all(|t| {
173                             let ty_params = t.trait_ref.substs.iter().skip(1).collect::<Vec<_>>();
174                             implements_trait(cx, ty_empty_region, t.def_id(), &ty_params)
175                         })
176                     },
177                 )
178             };
179
180             if_chain! {
181                 if !is_self(arg);
182                 if !ty.is_mutable_ptr();
183                 if !is_copy(cx, ty);
184                 if !allowed_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
185                 if !implements_borrow_trait;
186                 if !all_borrowable_trait;
187
188                 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.kind;
189                 if !moved_vars.contains(&canonical_id);
190                 then {
191                     if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
192                         continue;
193                     }
194
195                     // Dereference suggestion
196                     let sugg = |diag: &mut DiagnosticBuilder<'_>| {
197                         if let ty::Adt(def, ..) = ty.kind() {
198                             if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
199                                 if can_type_implement_copy(cx.tcx, cx.param_env, ty).is_ok() {
200                                     diag.span_help(span, "consider marking this type as `Copy`");
201                                 }
202                             }
203                         }
204
205                         let deref_span = spans_need_deref.get(&canonical_id);
206                         if_chain! {
207                             if is_type_diagnostic_item(cx, ty, sym::vec_type);
208                             if let Some(clone_spans) =
209                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
210                             if let TyKind::Path(QPath::Resolved(_, ref path)) = input.kind;
211                             if let Some(elem_ty) = path.segments.iter()
212                                 .find(|seg| seg.ident.name == sym::Vec)
213                                 .and_then(|ps| ps.args.as_ref())
214                                 .map(|params| params.args.iter().find_map(|arg| match arg {
215                                     GenericArg::Type(ty) => Some(ty),
216                                     _ => None,
217                                 }).unwrap());
218                             then {
219                                 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
220                                 diag.span_suggestion(
221                                     input.span,
222                                     "consider changing the type to",
223                                     slice_ty,
224                                     Applicability::Unspecified,
225                                 );
226
227                                 for (span, suggestion) in clone_spans {
228                                     diag.span_suggestion(
229                                         span,
230                                         &snippet_opt(cx, span)
231                                             .map_or(
232                                                 "change the call to".into(),
233                                                 |x| Cow::from(format!("change `{}` to", x)),
234                                             ),
235                                         suggestion.into(),
236                                         Applicability::Unspecified,
237                                     );
238                                 }
239
240                                 // cannot be destructured, no need for `*` suggestion
241                                 assert!(deref_span.is_none());
242                                 return;
243                             }
244                         }
245
246                         if is_type_diagnostic_item(cx, ty, sym::string_type) {
247                             if let Some(clone_spans) =
248                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
249                                 diag.span_suggestion(
250                                     input.span,
251                                     "consider changing the type to",
252                                     "&str".to_string(),
253                                     Applicability::Unspecified,
254                                 );
255
256                                 for (span, suggestion) in clone_spans {
257                                     diag.span_suggestion(
258                                         span,
259                                         &snippet_opt(cx, span)
260                                             .map_or(
261                                                 "change the call to".into(),
262                                                 |x| Cow::from(format!("change `{}` to", x))
263                                             ),
264                                         suggestion.into(),
265                                         Applicability::Unspecified,
266                                     );
267                                 }
268
269                                 assert!(deref_span.is_none());
270                                 return;
271                             }
272                         }
273
274                         let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
275
276                         // Suggests adding `*` to dereference the added reference.
277                         if let Some(deref_span) = deref_span {
278                             spans.extend(
279                                 deref_span
280                                     .iter()
281                                     .cloned()
282                                     .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
283                             );
284                             spans.sort_by_key(|&(span, _)| span);
285                         }
286                         multispan_sugg(diag, "consider taking a reference instead", spans);
287                     };
288
289                     span_lint_and_then(
290                         cx,
291                         NEEDLESS_PASS_BY_VALUE,
292                         input.span,
293                         "this argument is passed by value, but not consumed in the function body",
294                         sugg,
295                     );
296                 }
297             }
298         }
299     }
300 }
301
302 /// Functions marked with these attributes must have the exact signature.
303 fn requires_exact_signature(attrs: &[Attribute]) -> bool {
304     attrs.iter().any(|attr| {
305         [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
306             .iter()
307             .any(|&allow| attr.has_name(allow))
308     })
309 }
310
311 #[derive(Default)]
312 struct MovedVariablesCtxt {
313     moved_vars: FxHashSet<HirId>,
314     /// Spans which need to be prefixed with `*` for dereferencing the
315     /// suggested additional reference.
316     spans_need_deref: FxHashMap<HirId, FxHashSet<Span>>,
317 }
318
319 impl MovedVariablesCtxt {
320     fn move_common(&mut self, cmt: &euv::PlaceWithHirId<'_>) {
321         if let euv::PlaceBase::Local(vid) = cmt.place.base {
322             self.moved_vars.insert(vid);
323         }
324     }
325 }
326
327 impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt {
328     fn consume(&mut self, cmt: &euv::PlaceWithHirId<'tcx>, _: HirId, mode: euv::ConsumeMode) {
329         if let euv::ConsumeMode::Move = mode {
330             self.move_common(cmt);
331         }
332     }
333
334     fn borrow(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {}
335
336     fn mutate(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId) {}
337 }