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