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