]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/trivially_copy_pass_by_ref.rs
Auto merge of #5334 - flip1995:backport_remerge, r=flip1995
[rust.git] / clippy_lints / src / trivially_copy_pass_by_ref.rs
index 319f6311e88e01ff30a04d67a9b26a604ac6cd1b..0f00ed6c1fadd94229e05d3452d1890e3ec1e23c 100644 (file)
@@ -1,19 +1,18 @@
 use std::cmp;
 
-use crate::utils::{in_macro_or_desugar, is_copy, is_self_ty, snippet, span_lint_and_sugg};
+use crate::utils::{is_copy, is_self_ty, snippet, span_lint_and_sugg};
 use if_chain::if_chain;
-use matches::matches;
-use rustc::hir;
-use rustc::hir::intravisit::FnKind;
-use rustc::hir::*;
-use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
-use rustc::session::config::Config as SessionConfig;
-use rustc::ty::{self, FnSig};
-use rustc::{declare_tool_lint, impl_lint_pass};
+use rustc::ty;
 use rustc_errors::Applicability;
+use rustc_hir as hir;
+use rustc_hir::intravisit::FnKind;
+use rustc_hir::{Body, FnDecl, HirId, ItemKind, MutTy, Mutability, Node};
+use rustc_lint::{LateContext, LateLintPass};
+use rustc_session::config::Config as SessionConfig;
+use rustc_session::{declare_tool_lint, impl_lint_pass};
+use rustc_span::Span;
 use rustc_target::abi::LayoutOf;
 use rustc_target::spec::abi::Abi;
-use syntax_pos::Span;
 
 declare_clippy_lint! {
     /// **What it does:** Checks for functions taking arguments by reference, where
     /// each other.
     ///
     /// **Example:**
+    ///
     /// ```rust
-    /// fn foo(v: &u32) {
-    ///     assert_eq!(v, 42);
-    /// }
-    /// // should be
-    /// fn foo(v: u32) {
-    ///     assert_eq!(v, 42);
-    /// }
+    /// // Bad
+    /// fn foo(v: &u32) {}
+    /// ```
+    ///
+    /// ```rust
+    /// // Better
+    /// fn foo(v: u32) {}
     /// ```
     pub TRIVIALLY_COPY_PASS_BY_REF,
     perf,
     "functions taking small copyable arguments by reference"
 }
 
+#[derive(Copy, Clone)]
 pub struct TriviallyCopyPassByRef {
     limit: u64,
 }
@@ -60,10 +61,11 @@ pub struct TriviallyCopyPassByRef {
 impl<'a, 'tcx> TriviallyCopyPassByRef {
     pub fn new(limit: Option<u64>, target: &SessionConfig) -> Self {
         let limit = limit.unwrap_or_else(|| {
-            let bit_width = target.usize_ty.bit_width().expect("usize should have a width") as u64;
+            let bit_width = u64::from(target.ptr_width);
             // Cap the calculated bit width at 32-bits to reduce
             // portability problems between 32 and 64-bit targets
             let bit_width = cmp::min(bit_width, 32);
+            #[allow(clippy::integer_division)]
             let byte_width = bit_width / 8;
             // Use a limit of 2 times the register byte width
             byte_width * 2
@@ -71,30 +73,22 @@ pub fn new(limit: Option<u64>, target: &SessionConfig) -> Self {
         Self { limit }
     }
 
-    fn check_trait_method(&mut self, cx: &LateContext<'_, 'tcx>, item: &TraitItemRef) {
-        let method_def_id = cx.tcx.hir().local_def_id_from_hir_id(item.id.hir_id);
-        let method_sig = cx.tcx.fn_sig(method_def_id);
-        let method_sig = cx.tcx.erase_late_bound_regions(&method_sig);
+    fn check_poly_fn(&mut self, cx: &LateContext<'_, 'tcx>, hir_id: HirId, decl: &FnDecl<'_>, span: Option<Span>) {
+        let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
 
-        let decl = match cx.tcx.hir().fn_decl_by_hir_id(item.id.hir_id) {
-            Some(b) => b,
-            None => return,
-        };
-
-        self.check_poly_fn(cx, &decl, &method_sig, None);
-    }
+        let fn_sig = cx.tcx.fn_sig(fn_def_id);
+        let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
 
-    fn check_poly_fn(&mut self, cx: &LateContext<'_, 'tcx>, decl: &FnDecl, sig: &FnSig<'tcx>, span: Option<Span>) {
         // Use lifetimes to determine if we're returning a reference to the
         // argument. In that case we can't switch to pass-by-value as the
         // argument will not live long enough.
-        let output_lts = match sig.output().sty {
+        let output_lts = match fn_sig.output().kind {
             ty::Ref(output_lt, _, _) => vec![output_lt],
             ty::Adt(_, substs) => substs.regions().collect(),
             _ => vec![],
         };
 
-        for (input, &ty) in decl.inputs.iter().zip(sig.inputs()) {
+        for (input, &ty) in decl.inputs.iter().zip(fn_sig.inputs()) {
             // All spans generated from a proc-macro invocation are the same...
             match span {
                 Some(s) if s == input.span => return,
@@ -102,12 +96,12 @@ fn check_poly_fn(&mut self, cx: &LateContext<'_, 'tcx>, decl: &FnDecl, sig: &FnS
             }
 
             if_chain! {
-                if let ty::Ref(input_lt, ty, Mutability::MutImmutable) = ty.sty;
+                if let ty::Ref(input_lt, ty, Mutability::Not) = ty.kind;
                 if !output_lts.contains(&input_lt);
                 if is_copy(cx, ty);
                 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
                 if size <= self.limit;
-                if let hir::TyKind::Rptr(_, MutTy { ty: ref decl_ty, .. }) = input.node;
+                if let hir::TyKind::Rptr(_, MutTy { ty: ref decl_ty, .. }) = input.kind;
                 then {
                     let value_type = if is_self_ty(decl_ty) {
                         "self".into()
@@ -127,25 +121,18 @@ fn check_poly_fn(&mut self, cx: &LateContext<'_, 'tcx>, decl: &FnDecl, sig: &FnS
             }
         }
     }
-
-    fn check_trait_items(&mut self, cx: &LateContext<'_, '_>, trait_items: &[TraitItemRef]) {
-        for item in trait_items {
-            if let AssocItemKind::Method { .. } = item.kind {
-                self.check_trait_method(cx, item);
-            }
-        }
-    }
 }
 
 impl_lint_pass!(TriviallyCopyPassByRef => [TRIVIALLY_COPY_PASS_BY_REF]);
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TriviallyCopyPassByRef {
-    fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
-        if in_macro_or_desugar(item.span) {
+    fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
+        if item.span.from_expansion() {
             return;
         }
-        if let ItemKind::Trait(_, _, _, _, ref trait_items) = item.node {
-            self.check_trait_items(cx, trait_items);
+
+        if let hir::TraitItemKind::Fn(method_sig, _) = &item.kind {
+            self.check_poly_fn(cx, item.hir_id, &*method_sig.decl, None);
         }
     }
 
@@ -153,12 +140,12 @@ fn check_fn(
         &mut self,
         cx: &LateContext<'a, 'tcx>,
         kind: FnKind<'tcx>,
-        decl: &'tcx FnDecl,
-        _body: &'tcx Body,
+        decl: &'tcx FnDecl<'_>,
+        _body: &'tcx Body<'_>,
         span: Span,
         hir_id: HirId,
     ) {
-        if in_macro_or_desugar(span) {
+        if span.from_expansion() {
             return;
         }
 
@@ -178,23 +165,14 @@ fn check_fn(
         }
 
         // Exclude non-inherent impls
-        if let Some(Node::Item(item)) = cx
-            .tcx
-            .hir()
-            .find_by_hir_id(cx.tcx.hir().get_parent_node_by_hir_id(hir_id))
-        {
-            if matches!(item.node, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
+        if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
+            if matches!(item.kind, ItemKind::Impl{ of_trait: Some(_), .. } |
                 ItemKind::Trait(..))
             {
                 return;
             }
         }
 
-        let fn_def_id = cx.tcx.hir().local_def_id_from_hir_id(hir_id);
-
-        let fn_sig = cx.tcx.fn_sig(fn_def_id);
-        let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
-
-        self.check_poly_fn(cx, decl, &fn_sig, Some(span));
+        self.check_poly_fn(cx, hir_id, decl, Some(span));
     }
 }