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