]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/trivially_copy_pass_by_ref.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / trivially_copy_pass_by_ref.rs
1 use std::cmp;
2
3 use crate::utils::{in_macro, is_copy, is_self_ty, snippet, span_lint_and_sugg};
4 use if_chain::if_chain;
5 use matches::matches;
6 use rustc::hir;
7 use rustc::hir::intravisit::FnKind;
8 use rustc::hir::*;
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::session::config::Config as SessionConfig;
11 use rustc::ty::{self, FnSig};
12 use rustc::{declare_tool_lint, lint_array};
13 use rustc_errors::Applicability;
14 use rustc_target::abi::LayoutOf;
15 use rustc_target::spec::abi::Abi;
16 use syntax_pos::Span;
17
18 declare_clippy_lint! {
19     /// **What it does:** Checks for functions taking arguments by reference, where
20     /// the argument type is `Copy` and small enough to be more efficient to always
21     /// pass by value.
22     ///
23     /// **Why is this bad?** In many calling conventions instances of structs will
24     /// be passed through registers if they fit into two or less general purpose
25     /// registers.
26     ///
27     /// **Known problems:** This lint is target register size dependent, it is
28     /// limited to 32-bit to try and reduce portability problems between 32 and
29     /// 64-bit, but if you are compiling for 8 or 16-bit targets then the limit
30     /// will be different.
31     ///
32     /// The configuration option `trivial_copy_size_limit` can be set to override
33     /// this limit for a project.
34     ///
35     /// This lint attempts to allow passing arguments by reference if a reference
36     /// to that argument is returned. This is implemented by comparing the lifetime
37     /// of the argument and return value for equality. However, this can cause
38     /// false positives in cases involving multiple lifetimes that are bounded by
39     /// each other.
40     ///
41     /// **Example:**
42     /// ```rust
43     /// fn foo(v: &u32) {
44     ///     assert_eq!(v, 42);
45     /// }
46     /// // should be
47     /// fn foo(v: u32) {
48     ///     assert_eq!(v, 42);
49     /// }
50     /// ```
51     pub TRIVIALLY_COPY_PASS_BY_REF,
52     perf,
53     "functions taking small copyable arguments by reference"
54 }
55
56 pub struct TriviallyCopyPassByRef {
57     limit: u64,
58 }
59
60 impl<'a, 'tcx> TriviallyCopyPassByRef {
61     pub fn new(limit: Option<u64>, target: &SessionConfig) -> Self {
62         let limit = limit.unwrap_or_else(|| {
63             let bit_width = target.usize_ty.bit_width().expect("usize should have a width") as u64;
64             // Cap the calculated bit width at 32-bits to reduce
65             // portability problems between 32 and 64-bit targets
66             let bit_width = cmp::min(bit_width, 32);
67             let byte_width = bit_width / 8;
68             // Use a limit of 2 times the register bit width
69             byte_width * 2
70         });
71         Self { limit }
72     }
73
74     fn check_trait_method(&mut self, cx: &LateContext<'_, 'tcx>, item: &TraitItemRef) {
75         let method_def_id = cx.tcx.hir().local_def_id_from_hir_id(item.id.hir_id);
76         let method_sig = cx.tcx.fn_sig(method_def_id);
77         let method_sig = cx.tcx.erase_late_bound_regions(&method_sig);
78
79         let decl = match cx.tcx.hir().fn_decl_by_hir_id(item.id.hir_id) {
80             Some(b) => b,
81             None => return,
82         };
83
84         self.check_poly_fn(cx, &decl, &method_sig, None);
85     }
86
87     fn check_poly_fn(&mut self, cx: &LateContext<'_, 'tcx>, decl: &FnDecl, sig: &FnSig<'tcx>, span: Option<Span>) {
88         // Use lifetimes to determine if we're returning a reference to the
89         // argument. In that case we can't switch to pass-by-value as the
90         // argument will not live long enough.
91         let output_lts = match sig.output().sty {
92             ty::Ref(output_lt, _, _) => vec![output_lt],
93             ty::Adt(_, substs) => substs.regions().collect(),
94             _ => vec![],
95         };
96
97         for (input, &ty) in decl.inputs.iter().zip(sig.inputs()) {
98             // All spans generated from a proc-macro invocation are the same...
99             match span {
100                 Some(s) if s == input.span => return,
101                 _ => (),
102             }
103
104             if_chain! {
105                 if let ty::Ref(input_lt, ty, Mutability::MutImmutable) = ty.sty;
106                 if !output_lts.contains(&input_lt);
107                 if is_copy(cx, ty);
108                 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
109                 if size <= self.limit;
110                 if let hir::TyKind::Rptr(_, MutTy { ty: ref decl_ty, .. }) = input.node;
111                 then {
112                     let value_type = if is_self_ty(decl_ty) {
113                         "self".into()
114                     } else {
115                         snippet(cx, decl_ty.span, "_").into()
116                     };
117                     span_lint_and_sugg(
118                         cx,
119                         TRIVIALLY_COPY_PASS_BY_REF,
120                         input.span,
121                         "this argument is passed by reference, but would be more efficient if passed by value",
122                         "consider passing by value instead",
123                         value_type,
124                         Applicability::Unspecified,
125                     );
126                 }
127             }
128         }
129     }
130
131     fn check_trait_items(&mut self, cx: &LateContext<'_, '_>, trait_items: &[TraitItemRef]) {
132         for item in trait_items {
133             if let AssociatedItemKind::Method { .. } = item.kind {
134                 self.check_trait_method(cx, item);
135             }
136         }
137     }
138 }
139
140 impl LintPass for TriviallyCopyPassByRef {
141     fn get_lints(&self) -> LintArray {
142         lint_array![TRIVIALLY_COPY_PASS_BY_REF]
143     }
144
145     fn name(&self) -> &'static str {
146         "TrivallyCopyPassByRef"
147     }
148 }
149
150 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TriviallyCopyPassByRef {
151     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
152         if in_macro(item.span) {
153             return;
154         }
155         if let ItemKind::Trait(_, _, _, _, ref trait_items) = item.node {
156             self.check_trait_items(cx, trait_items);
157         }
158     }
159
160     fn check_fn(
161         &mut self,
162         cx: &LateContext<'a, 'tcx>,
163         kind: FnKind<'tcx>,
164         decl: &'tcx FnDecl,
165         _body: &'tcx Body,
166         span: Span,
167         hir_id: HirId,
168     ) {
169         if in_macro(span) {
170             return;
171         }
172
173         match kind {
174             FnKind::ItemFn(.., header, _, attrs) => {
175                 if header.abi != Abi::Rust {
176                     return;
177                 }
178                 for a in attrs {
179                     if a.meta_item_list().is_some() && a.check_name("proc_macro_derive") {
180                         return;
181                     }
182                 }
183             },
184             FnKind::Method(..) => (),
185             _ => return,
186         }
187
188         // Exclude non-inherent impls
189         if let Some(Node::Item(item)) = cx
190             .tcx
191             .hir()
192             .find_by_hir_id(cx.tcx.hir().get_parent_node_by_hir_id(hir_id))
193         {
194             if matches!(item.node, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
195                 ItemKind::Trait(..))
196             {
197                 return;
198             }
199         }
200
201         let fn_def_id = cx.tcx.hir().local_def_id_from_hir_id(hir_id);
202
203         let fn_sig = cx.tcx.fn_sig(fn_def_id);
204         let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
205
206         self.check_poly_fn(cx, decl, &fn_sig, Some(span));
207     }
208 }