]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs
Re-add #[allow(unused)] attr
[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::source::snippet;
6 use clippy_utils::ty::{for_each_top_level_late_bound_region, is_copy};
7 use clippy_utils::{is_self, is_self_ty};
8 use core::ops::ControlFlow;
9 use if_chain::if_chain;
10 use rustc_ast::attr;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_errors::Applicability;
13 use rustc_hir as hir;
14 use rustc_hir::intravisit::FnKind;
15 use rustc_hir::{BindingAnnotation, Body, FnDecl, HirId, Impl, ItemKind, MutTy, Mutability, Node, PatKind};
16 use rustc_lint::{LateContext, LateLintPass};
17 use rustc_middle::ty::adjustment::{Adjust, PointerCast};
18 use rustc_middle::ty::layout::LayoutOf;
19 use rustc_middle::ty::{self, RegionKind};
20 use rustc_session::{declare_tool_lint, impl_lint_pass};
21 use rustc_span::def_id::LocalDefId;
22 use rustc_span::{sym, Span};
23 use rustc_target::spec::abi::Abi;
24 use rustc_target::spec::Target;
25
26 declare_clippy_lint! {
27     /// ### What it does
28     /// Checks for functions taking arguments by reference, where
29     /// the argument type is `Copy` and small enough to be more efficient to always
30     /// pass by value.
31     ///
32     /// ### Why is this bad?
33     /// In many calling conventions instances of structs will
34     /// be passed through registers if they fit into two or less general purpose
35     /// registers.
36     ///
37     /// ### Known problems
38     /// This lint is target register size dependent, it is
39     /// limited to 32-bit to try and reduce portability problems between 32 and
40     /// 64-bit, but if you are compiling for 8 or 16-bit targets then the limit
41     /// will be different.
42     ///
43     /// The configuration option `trivial_copy_size_limit` can be set to override
44     /// this limit for a project.
45     ///
46     /// This lint attempts to allow passing arguments by reference if a reference
47     /// to that argument is returned. This is implemented by comparing the lifetime
48     /// of the argument and return value for equality. However, this can cause
49     /// false positives in cases involving multiple lifetimes that are bounded by
50     /// each other.
51     ///
52     /// Also, it does not take account of other similar cases where getting memory addresses
53     /// matters; namely, returning the pointer to the argument in question,
54     /// and passing the argument, as both references and pointers,
55     /// to a function that needs the memory address. For further details, refer to
56     /// [this issue](https://github.com/rust-lang/rust-clippy/issues/5953)
57     /// that explains a real case in which this false positive
58     /// led to an **undefined behavior** introduced with unsafe code.
59     ///
60     /// ### Example
61     ///
62     /// ```rust
63     /// fn foo(v: &u32) {}
64     /// ```
65     ///
66     /// Use instead:
67     /// ```rust
68     /// fn foo(v: u32) {}
69     /// ```
70     #[clippy::version = "pre 1.29.0"]
71     pub TRIVIALLY_COPY_PASS_BY_REF,
72     pedantic,
73     "functions taking small copyable arguments by reference"
74 }
75
76 declare_clippy_lint! {
77     /// ### What it does
78     /// Checks for functions taking arguments by value, where
79     /// the argument type is `Copy` and large enough to be worth considering
80     /// passing by reference. Does not trigger if the function is being exported,
81     /// because that might induce API breakage, if the parameter is declared as mutable,
82     /// or if the argument is a `self`.
83     ///
84     /// ### Why is this bad?
85     /// Arguments passed by value might result in an unnecessary
86     /// shallow copy, taking up more space in the stack and requiring a call to
87     /// `memcpy`, which can be expensive.
88     ///
89     /// ### Example
90     /// ```rust
91     /// #[derive(Clone, Copy)]
92     /// struct TooLarge([u8; 2048]);
93     ///
94     /// fn foo(v: TooLarge) {}
95     /// ```
96     ///
97     /// Use instead:
98     /// ```rust
99     /// # #[derive(Clone, Copy)]
100     /// # struct TooLarge([u8; 2048]);
101     /// fn foo(v: &TooLarge) {}
102     /// ```
103     #[clippy::version = "1.49.0"]
104     pub LARGE_TYPES_PASSED_BY_VALUE,
105     pedantic,
106     "functions taking large arguments by value"
107 }
108
109 #[derive(Copy, Clone)]
110 pub struct PassByRefOrValue {
111     ref_min_size: u64,
112     value_max_size: u64,
113     avoid_breaking_exported_api: bool,
114 }
115
116 impl<'tcx> PassByRefOrValue {
117     pub fn new(
118         ref_min_size: Option<u64>,
119         value_max_size: u64,
120         avoid_breaking_exported_api: bool,
121         target: &Target,
122     ) -> Self {
123         let ref_min_size = ref_min_size.unwrap_or_else(|| {
124             let bit_width = u64::from(target.pointer_width);
125             // Cap the calculated bit width at 32-bits to reduce
126             // portability problems between 32 and 64-bit targets
127             let bit_width = cmp::min(bit_width, 32);
128             #[expect(clippy::integer_division)]
129             let byte_width = bit_width / 8;
130             // Use a limit of 2 times the register byte width
131             byte_width * 2
132         });
133
134         Self {
135             ref_min_size,
136             value_max_size,
137             avoid_breaking_exported_api,
138         }
139     }
140
141     fn check_poly_fn(&mut self, cx: &LateContext<'tcx>, def_id: LocalDefId, decl: &FnDecl<'_>, span: Option<Span>) {
142         if self.avoid_breaking_exported_api && cx.effective_visibilities.is_exported(def_id) {
143             return;
144         }
145
146         let fn_sig = cx.tcx.fn_sig(def_id);
147         let fn_body = cx.enclosing_body.map(|id| cx.tcx.hir().body(id));
148
149         // Gather all the lifetimes found in the output type which may affect whether
150         // `TRIVIALLY_COPY_PASS_BY_REF` should be linted.
151         let mut output_regions = FxHashSet::default();
152         for_each_top_level_late_bound_region(fn_sig.skip_binder().output(), |region| -> ControlFlow<!> {
153             output_regions.insert(region);
154             ControlFlow::Continue(())
155         });
156
157         for (index, (input, ty)) in iter::zip(
158             decl.inputs,
159             fn_sig.skip_binder().inputs().iter().map(|&ty| fn_sig.rebind(ty)),
160         )
161         .enumerate()
162         {
163             // All spans generated from a proc-macro invocation are the same...
164             match span {
165                 Some(s) if s == input.span => continue,
166                 _ => (),
167             }
168
169             match *ty.skip_binder().kind() {
170                 ty::Ref(lt, ty, Mutability::Not) => {
171                     match lt.kind() {
172                         RegionKind::ReLateBound(index, region)
173                             if index.as_u32() == 0 && output_regions.contains(&region) =>
174                         {
175                             continue;
176                         },
177                         // Early bound regions on functions are either from the containing item, are bounded by another
178                         // lifetime, or are used as a bound for a type or lifetime.
179                         RegionKind::ReEarlyBound(..) => continue,
180                         _ => (),
181                     }
182
183                     let ty = cx.tcx.erase_late_bound_regions(fn_sig.rebind(ty));
184                     if is_copy(cx, ty)
185                         && let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes())
186                         && size <= self.ref_min_size
187                         && let hir::TyKind::Ref(_, MutTy { ty: decl_ty, .. }) = input.kind
188                     {
189                         if let Some(typeck) = cx.maybe_typeck_results() {
190                             // Don't lint if an unsafe pointer is created.
191                             // TODO: Limit the check only to unsafe pointers to the argument (or part of the argument)
192                             //       which escape the current function.
193                             if typeck.node_types().iter().any(|(_, &ty)| ty.is_unsafe_ptr())
194                                 || typeck
195                                     .adjustments()
196                                     .iter()
197                                     .flat_map(|(_, a)| a)
198                                     .any(|a| matches!(a.kind, Adjust::Pointer(PointerCast::UnsafeFnPointer)))
199                             {
200                                 continue;
201                             }
202                         }
203                         let value_type = if fn_body.and_then(|body| body.params.get(index)).map_or(false, is_self) {
204                             "self".into()
205                         } else {
206                             snippet(cx, decl_ty.span, "_").into()
207                         };
208                         span_lint_and_sugg(
209                             cx,
210                             TRIVIALLY_COPY_PASS_BY_REF,
211                             input.span,
212                             &format!("this argument ({size} byte) is passed by reference, but would be more efficient if passed by value (limit: {} byte)", self.ref_min_size),
213                             "consider passing by value instead",
214                             value_type,
215                             Applicability::Unspecified,
216                         );
217                     }
218                 },
219
220                 ty::Adt(_, _) | ty::Array(_, _) | ty::Tuple(_) => {
221                     // if function has a body and parameter is annotated with mut, ignore
222                     if let Some(param) = fn_body.and_then(|body| body.params.get(index)) {
223                         match param.pat.kind {
224                             PatKind::Binding(BindingAnnotation::NONE, _, _, _) => {},
225                             _ => continue,
226                         }
227                     }
228                     let ty = cx.tcx.erase_late_bound_regions(ty);
229
230                     if_chain! {
231                         if is_copy(cx, ty);
232                         if !is_self_ty(input);
233                         if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
234                         if size > self.value_max_size;
235                         then {
236                             span_lint_and_sugg(
237                                 cx,
238                                 LARGE_TYPES_PASSED_BY_VALUE,
239                                 input.span,
240                                 &format!("this argument ({size} byte) is passed by value, but might be more efficient if passed by reference (limit: {} byte)", self.value_max_size),
241                                 "consider passing by reference instead",
242                                 format!("&{}", snippet(cx, input.span, "_")),
243                                 Applicability::MaybeIncorrect,
244                             );
245                         }
246                     }
247                 },
248
249                 _ => {},
250             }
251         }
252     }
253 }
254
255 impl_lint_pass!(PassByRefOrValue => [TRIVIALLY_COPY_PASS_BY_REF, LARGE_TYPES_PASSED_BY_VALUE]);
256
257 impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue {
258     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
259         if item.span.from_expansion() {
260             return;
261         }
262
263         if let hir::TraitItemKind::Fn(method_sig, _) = &item.kind {
264             self.check_poly_fn(cx, item.owner_id.def_id, method_sig.decl, None);
265         }
266     }
267
268     fn check_fn(
269         &mut self,
270         cx: &LateContext<'tcx>,
271         kind: FnKind<'tcx>,
272         decl: &'tcx FnDecl<'_>,
273         _body: &'tcx Body<'_>,
274         span: Span,
275         hir_id: HirId,
276     ) {
277         if span.from_expansion() {
278             return;
279         }
280
281         match kind {
282             FnKind::ItemFn(.., header) => {
283                 if header.abi != Abi::Rust {
284                     return;
285                 }
286                 let attrs = cx.tcx.hir().attrs(hir_id);
287                 for a in attrs {
288                     if let Some(meta_items) = a.meta_item_list() {
289                         if a.has_name(sym::proc_macro_derive)
290                             || (a.has_name(sym::inline) && attr::list_contains_name(&meta_items, sym::always))
291                         {
292                             return;
293                         }
294                     }
295                 }
296             },
297             FnKind::Method(..) => (),
298             FnKind::Closure => return,
299         }
300
301         // Exclude non-inherent impls
302         if let Some(Node::Item(item)) = cx.tcx.hir().find_parent(hir_id) {
303             if matches!(
304                 item.kind,
305                 ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..)
306             ) {
307                 return;
308             }
309         }
310
311         self.check_poly_fn(cx, cx.tcx.hir().local_def_id(hir_id), decl, Some(span));
312     }
313 }