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