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