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