]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/trivially_copy_pass_by_ref.rs
Auto merge of #5003 - JohnTitor:rustup, r=flip1995
[rust.git] / clippy_lints / src / trivially_copy_pass_by_ref.rs
1 use std::cmp;
2
3 use crate::utils::{is_copy, is_self_ty, snippet, span_lint_and_sugg};
4 use if_chain::if_chain;
5 use matches::matches;
6 use rustc::hir::intravisit::FnKind;
7 use rustc::impl_lint_pass;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use rustc::session::config::Config as SessionConfig;
10 use rustc::ty;
11 use rustc_errors::Applicability;
12 use rustc_hir as hir;
13 use rustc_hir::*;
14 use rustc_session::declare_tool_lint;
15 use rustc_span::Span;
16 use rustc_target::abi::LayoutOf;
17 use rustc_target::spec::abi::Abi;
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     perf,
55     "functions taking small copyable arguments by reference"
56 }
57
58 #[derive(Copy, Clone)]
59 pub struct TriviallyCopyPassByRef {
60     limit: u64,
61 }
62
63 impl<'a, 'tcx> TriviallyCopyPassByRef {
64     pub fn new(limit: Option<u64>, target: &SessionConfig) -> Self {
65         let limit = limit.unwrap_or_else(|| {
66             let bit_width = u64::from(target.ptr_width);
67             // Cap the calculated bit width at 32-bits to reduce
68             // portability problems between 32 and 64-bit targets
69             let bit_width = cmp::min(bit_width, 32);
70             #[allow(clippy::integer_division)]
71             let byte_width = bit_width / 8;
72             // Use a limit of 2 times the register byte width
73             byte_width * 2
74         });
75         Self { limit }
76     }
77
78     fn check_poly_fn(&mut self, cx: &LateContext<'_, 'tcx>, hir_id: HirId, decl: &FnDecl<'_>, span: Option<Span>) {
79         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
80
81         let fn_sig = cx.tcx.fn_sig(fn_def_id);
82         let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
83
84         // Use lifetimes to determine if we're returning a reference to the
85         // argument. In that case we can't switch to pass-by-value as the
86         // argument will not live long enough.
87         let output_lts = match fn_sig.output().kind {
88             ty::Ref(output_lt, _, _) => vec![output_lt],
89             ty::Adt(_, substs) => substs.regions().collect(),
90             _ => vec![],
91         };
92
93         for (input, &ty) in decl.inputs.iter().zip(fn_sig.inputs()) {
94             // All spans generated from a proc-macro invocation are the same...
95             match span {
96                 Some(s) if s == input.span => return,
97                 _ => (),
98             }
99
100             if_chain! {
101                 if let ty::Ref(input_lt, ty, Mutability::Not) = ty.kind;
102                 if !output_lts.contains(&input_lt);
103                 if is_copy(cx, ty);
104                 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
105                 if size <= self.limit;
106                 if let hir::TyKind::Rptr(_, MutTy { ty: ref decl_ty, .. }) = input.kind;
107                 then {
108                     let value_type = if is_self_ty(decl_ty) {
109                         "self".into()
110                     } else {
111                         snippet(cx, decl_ty.span, "_").into()
112                     };
113                     span_lint_and_sugg(
114                         cx,
115                         TRIVIALLY_COPY_PASS_BY_REF,
116                         input.span,
117                         &format!("this argument ({} byte) is passed by reference, but would be more efficient if passed by value (limit: {} byte)", size, self.limit),
118                         "consider passing by value instead",
119                         value_type,
120                         Applicability::Unspecified,
121                     );
122                 }
123             }
124         }
125     }
126 }
127
128 impl_lint_pass!(TriviallyCopyPassByRef => [TRIVIALLY_COPY_PASS_BY_REF]);
129
130 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TriviallyCopyPassByRef {
131     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
132         if item.span.from_expansion() {
133             return;
134         }
135
136         if let hir::TraitItemKind::Method(method_sig, _) = &item.kind {
137             self.check_poly_fn(cx, item.hir_id, &*method_sig.decl, None);
138         }
139     }
140
141     fn check_fn(
142         &mut self,
143         cx: &LateContext<'a, 'tcx>,
144         kind: FnKind<'tcx>,
145         decl: &'tcx FnDecl<'_>,
146         _body: &'tcx Body<'_>,
147         span: Span,
148         hir_id: HirId,
149     ) {
150         if span.from_expansion() {
151             return;
152         }
153
154         match kind {
155             FnKind::ItemFn(.., header, _, attrs) => {
156                 if header.abi != Abi::Rust {
157                     return;
158                 }
159                 for a in attrs {
160                     if a.meta_item_list().is_some() && a.check_name(sym!(proc_macro_derive)) {
161                         return;
162                     }
163                 }
164             },
165             FnKind::Method(..) => (),
166             _ => return,
167         }
168
169         // Exclude non-inherent impls
170         if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
171             if matches!(item.kind, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
172                 ItemKind::Trait(..))
173             {
174                 return;
175             }
176         }
177
178         self.check_poly_fn(cx, hir_id, decl, Some(span));
179     }
180 }