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