]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs
Rollup merge of #83571 - a1phyr:feature_const_slice_first_last, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / pass_by_ref_or_value.rs
1 use std::cmp;
2 use std::iter;
3
4 use clippy_utils::diagnostics::span_lint_and_sugg;
5 use clippy_utils::is_self_ty;
6 use clippy_utils::source::snippet;
7 use clippy_utils::ty::is_copy;
8 use if_chain::if_chain;
9 use rustc_ast::attr;
10 use rustc_errors::Applicability;
11 use rustc_hir as hir;
12 use rustc_hir::intravisit::FnKind;
13 use rustc_hir::{BindingAnnotation, Body, FnDecl, HirId, Impl, ItemKind, MutTy, Mutability, Node, PatKind};
14 use rustc_lint::{LateContext, LateLintPass};
15 use rustc_middle::ty;
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::{sym, Span};
18 use rustc_target::abi::LayoutOf;
19 use rustc_target::spec::abi::Abi;
20 use rustc_target::spec::Target;
21
22 declare_clippy_lint! {
23     /// **What it does:** Checks for functions taking arguments by reference, where
24     /// the argument type is `Copy` and small enough to be more efficient to always
25     /// pass by value.
26     ///
27     /// **Why is this bad?** In many calling conventions instances of structs will
28     /// be passed through registers if they fit into two or less general purpose
29     /// registers.
30     ///
31     /// **Known problems:** This lint is target register size dependent, it is
32     /// limited to 32-bit to try and reduce portability problems between 32 and
33     /// 64-bit, but if you are compiling for 8 or 16-bit targets then the limit
34     /// will be different.
35     ///
36     /// The configuration option `trivial_copy_size_limit` can be set to override
37     /// this limit for a project.
38     ///
39     /// This lint attempts to allow passing arguments by reference if a reference
40     /// to that argument is returned. This is implemented by comparing the lifetime
41     /// of the argument and return value for equality. However, this can cause
42     /// false positives in cases involving multiple lifetimes that are bounded by
43     /// each other.
44     ///
45     /// **Example:**
46     ///
47     /// ```rust
48     /// // Bad
49     /// fn foo(v: &u32) {}
50     /// ```
51     ///
52     /// ```rust
53     /// // Better
54     /// fn foo(v: u32) {}
55     /// ```
56     pub TRIVIALLY_COPY_PASS_BY_REF,
57     pedantic,
58     "functions taking small copyable arguments by reference"
59 }
60
61 declare_clippy_lint! {
62     /// **What it does:** Checks for functions taking arguments by value, where
63     /// the argument type is `Copy` and large enough to be worth considering
64     /// passing by reference. Does not trigger if the function is being exported,
65     /// because that might induce API breakage, if the parameter is declared as mutable,
66     /// or if the argument is a `self`.
67     ///
68     /// **Why is this bad?** Arguments passed by value might result in an unnecessary
69     /// shallow copy, taking up more space in the stack and requiring a call to
70     /// `memcpy`, which can be expensive.
71     ///
72     /// **Example:**
73     ///
74     /// ```rust
75     /// #[derive(Clone, Copy)]
76     /// struct TooLarge([u8; 2048]);
77     ///
78     /// // Bad
79     /// fn foo(v: TooLarge) {}
80     /// ```
81     /// ```rust
82     /// #[derive(Clone, Copy)]
83     /// struct TooLarge([u8; 2048]);
84     ///
85     /// // Good
86     /// fn foo(v: &TooLarge) {}
87     /// ```
88     pub LARGE_TYPES_PASSED_BY_VALUE,
89     pedantic,
90     "functions taking large arguments by value"
91 }
92
93 #[derive(Copy, Clone)]
94 pub struct PassByRefOrValue {
95     ref_min_size: u64,
96     value_max_size: u64,
97 }
98
99 impl<'tcx> PassByRefOrValue {
100     pub fn new(ref_min_size: Option<u64>, value_max_size: u64, target: &Target) -> Self {
101         let ref_min_size = ref_min_size.unwrap_or_else(|| {
102             let bit_width = u64::from(target.pointer_width);
103             // Cap the calculated bit width at 32-bits to reduce
104             // portability problems between 32 and 64-bit targets
105             let bit_width = cmp::min(bit_width, 32);
106             #[allow(clippy::integer_division)]
107             let byte_width = bit_width / 8;
108             // Use a limit of 2 times the register byte width
109             byte_width * 2
110         });
111
112         Self {
113             ref_min_size,
114             value_max_size,
115         }
116     }
117
118     fn check_poly_fn(&mut self, cx: &LateContext<'tcx>, hir_id: HirId, decl: &FnDecl<'_>, span: Option<Span>) {
119         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
120
121         let fn_sig = cx.tcx.fn_sig(fn_def_id);
122         let fn_sig = cx.tcx.erase_late_bound_regions(fn_sig);
123
124         let fn_body = cx.enclosing_body.map(|id| cx.tcx.hir().body(id));
125
126         for (index, (input, &ty)) in iter::zip(decl.inputs, fn_sig.inputs()).enumerate() {
127             // All spans generated from a proc-macro invocation are the same...
128             match span {
129                 Some(s) if s == input.span => return,
130                 _ => (),
131             }
132
133             match ty.kind() {
134                 ty::Ref(input_lt, ty, Mutability::Not) => {
135                     // Use lifetimes to determine if we're returning a reference to the
136                     // argument. In that case we can't switch to pass-by-value as the
137                     // argument will not live long enough.
138                     let output_lts = match *fn_sig.output().kind() {
139                         ty::Ref(output_lt, _, _) => vec![output_lt],
140                         ty::Adt(_, substs) => substs.regions().collect(),
141                         _ => vec![],
142                     };
143
144                     if_chain! {
145                         if !output_lts.contains(&input_lt);
146                         if is_copy(cx, ty);
147                         if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
148                         if size <= self.ref_min_size;
149                         if let hir::TyKind::Rptr(_, MutTy { ty: ref decl_ty, .. }) = input.kind;
150                         then {
151                             let value_type = if is_self_ty(decl_ty) {
152                                 "self".into()
153                             } else {
154                                 snippet(cx, decl_ty.span, "_").into()
155                             };
156                             span_lint_and_sugg(
157                                 cx,
158                                 TRIVIALLY_COPY_PASS_BY_REF,
159                                 input.span,
160                                 &format!("this argument ({} byte) is passed by reference, but would be more efficient if passed by value (limit: {} byte)", size, self.ref_min_size),
161                                 "consider passing by value instead",
162                                 value_type,
163                                 Applicability::Unspecified,
164                             );
165                         }
166                     }
167                 },
168
169                 ty::Adt(_, _) | ty::Array(_, _) | ty::Tuple(_) => {
170                     // if function has a body and parameter is annotated with mut, ignore
171                     if let Some(param) = fn_body.and_then(|body| body.params.get(index)) {
172                         match param.pat.kind {
173                             PatKind::Binding(BindingAnnotation::Unannotated, _, _, _) => {},
174                             _ => continue,
175                         }
176                     }
177
178                     if_chain! {
179                         if !cx.access_levels.is_exported(hir_id);
180                         if is_copy(cx, ty);
181                         if !is_self_ty(input);
182                         if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
183                         if size > self.value_max_size;
184                         then {
185                             span_lint_and_sugg(
186                                 cx,
187                                 LARGE_TYPES_PASSED_BY_VALUE,
188                                 input.span,
189                                 &format!("this argument ({} byte) is passed by value, but might be more efficient if passed by reference (limit: {} byte)", size, self.value_max_size),
190                                 "consider passing by reference instead",
191                                 format!("&{}", snippet(cx, input.span, "_")),
192                                 Applicability::MaybeIncorrect,
193                             );
194                         }
195                     }
196                 },
197
198                 _ => {},
199             }
200         }
201     }
202 }
203
204 impl_lint_pass!(PassByRefOrValue => [TRIVIALLY_COPY_PASS_BY_REF, LARGE_TYPES_PASSED_BY_VALUE]);
205
206 impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue {
207     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
208         if item.span.from_expansion() {
209             return;
210         }
211
212         if let hir::TraitItemKind::Fn(method_sig, _) = &item.kind {
213             self.check_poly_fn(cx, item.hir_id(), &*method_sig.decl, None);
214         }
215     }
216
217     fn check_fn(
218         &mut self,
219         cx: &LateContext<'tcx>,
220         kind: FnKind<'tcx>,
221         decl: &'tcx FnDecl<'_>,
222         _body: &'tcx Body<'_>,
223         span: Span,
224         hir_id: HirId,
225     ) {
226         if span.from_expansion() {
227             return;
228         }
229
230         match kind {
231             FnKind::ItemFn(.., header, _) => {
232                 if header.abi != Abi::Rust {
233                     return;
234                 }
235                 let attrs = cx.tcx.hir().attrs(hir_id);
236                 for a in attrs {
237                     if let Some(meta_items) = a.meta_item_list() {
238                         if a.has_name(sym::proc_macro_derive)
239                             || (a.has_name(sym::inline) && attr::list_contains_name(&meta_items, sym::always))
240                         {
241                             return;
242                         }
243                     }
244                 }
245             },
246             FnKind::Method(..) => (),
247             FnKind::Closure => return,
248         }
249
250         // Exclude non-inherent impls
251         if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
252             if matches!(
253                 item.kind,
254                 ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..)
255             ) {
256                 return;
257             }
258         }
259
260         self.check_poly_fn(cx, hir_id, decl, Some(span));
261     }
262 }