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