]> git.lizzy.rs Git - rust.git/commitdiff
needless-lifetime - fix nested elision site FPs
authorTim Nielens <tim.nielens@gmail.com>
Thu, 27 Aug 2020 21:22:32 +0000 (23:22 +0200)
committerTim Nielens <tim.nielens@gmail.com>
Sun, 6 Sep 2020 21:06:58 +0000 (23:06 +0200)
clippy_lints/src/lifetimes.rs
clippy_lints/src/utils/paths.rs
tests/ui/needless_lifetimes.rs
tests/ui/needless_lifetimes.stderr

index 4df6827d77f94027551ba7663b1cace0af537c88..ab6e34d201c68e268eb84008836b83031d539444 100644 (file)
@@ -1,13 +1,14 @@
 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
 use rustc_hir::def::{DefKind, Res};
 use rustc_hir::intravisit::{
-    walk_fn_decl, walk_generic_param, walk_generics, walk_param_bound, walk_ty, NestedVisitorMap, Visitor,
+    walk_fn_decl, walk_generic_param, walk_generics, walk_param_bound, walk_trait_ref, walk_ty, NestedVisitorMap,
+    Visitor,
 };
 use rustc_hir::FnRetTy::Return;
 use rustc_hir::{
     BodyId, FnDecl, GenericArg, GenericBound, GenericParam, GenericParamKind, Generics, ImplItem, ImplItemKind, Item,
-    ItemKind, Lifetime, LifetimeName, ParamName, QPath, TraitBoundModifier, TraitFn, TraitItem, TraitItemKind, Ty,
-    TyKind, WhereClause, WherePredicate,
+    ItemKind, Lifetime, LifetimeName, ParamName, QPath, TraitBoundModifier, TraitFn, TraitItem, TraitItemKind,
+    TraitRef, Ty, TyKind, WhereClause, WherePredicate,
 };
 use rustc_lint::{LateContext, LateLintPass};
 use rustc_middle::hir::map::Map;
@@ -15,7 +16,8 @@
 use rustc_span::source_map::Span;
 use rustc_span::symbol::{kw, Symbol};
 
-use crate::utils::{in_macro, last_path_segment, span_lint, trait_ref_of_method};
+use crate::utils::paths;
+use crate::utils::{get_trait_def_id, in_macro, last_path_segment, span_lint, trait_ref_of_method};
 
 declare_clippy_lint! {
     /// **What it does:** Checks for lifetime annotations which can be removed by
@@ -127,6 +129,14 @@ fn check_fn_inner<'tcx>(
         return;
     }
 
+    // fn pointers and closure trait bounds are also lifetime elision sites. This lint does not
+    // support nested elision sites in a fn item.
+    if FnPointerOrClosureTraitBoundFinder::find_in_generics(cx, generics)
+        || FnPointerOrClosureTraitBoundFinder::find_in_fn_decl(cx, decl)
+    {
+        return;
+    }
+
     let mut bounds_lts = Vec::new();
     let types = generics
         .params
@@ -523,3 +533,54 @@ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
         NestedVisitorMap::None
     }
 }
+
+const CLOSURE_TRAIT_BOUNDS: [&[&str]; 3] = [&paths::FN, &paths::FN_MUT, &paths::FN_ONCE];
+
+struct FnPointerOrClosureTraitBoundFinder<'a, 'tcx> {
+    cx: &'a LateContext<'tcx>,
+    found: bool,
+}
+
+impl<'a, 'tcx> FnPointerOrClosureTraitBoundFinder<'a, 'tcx> {
+    fn find_in_generics(cx: &'a LateContext<'tcx>, generics: &'tcx Generics<'tcx>) -> bool {
+        let mut finder = Self { cx, found: false };
+        finder.visit_generics(generics);
+        finder.found
+    }
+
+    fn find_in_fn_decl(cx: &'a LateContext<'tcx>, generics: &'tcx FnDecl<'tcx>) -> bool {
+        let mut finder = Self { cx, found: false };
+        finder.visit_fn_decl(generics);
+        finder.found
+    }
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for FnPointerOrClosureTraitBoundFinder<'a, 'tcx> {
+    type Map = Map<'tcx>;
+    fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+        NestedVisitorMap::None
+    }
+
+    fn visit_trait_ref(&mut self, tref: &'tcx TraitRef<'tcx>) {
+        if CLOSURE_TRAIT_BOUNDS
+            .iter()
+            .any(|trait_path| tref.trait_def_id() == get_trait_def_id(self.cx, trait_path))
+        {
+            self.found = true;
+        }
+        walk_trait_ref(self, tref);
+    }
+
+    fn visit_ty(&mut self, ty: &'tcx Ty<'tcx>) {
+        match ty.kind {
+            TyKind::BareFn(..) => self.found = true,
+            TyKind::OpaqueDef(item_id, _) => {
+                let map = self.cx.tcx.hir();
+                let item = map.expect_item(item_id.id);
+                self.visit_item(item);
+            },
+            _ => (),
+        }
+        walk_ty(self, ty);
+    }
+}
index d44854aefe97acfd2c3943657ac107e428ecde8d..9837759fd5efe70862e03defeb4580ab4e0c40a5 100644 (file)
@@ -42,6 +42,9 @@
 pub const FMT_ARGUMENTS_NEW_V1: [&str; 4] = ["core", "fmt", "Arguments", "new_v1"];
 pub const FMT_ARGUMENTS_NEW_V1_FORMATTED: [&str; 4] = ["core", "fmt", "Arguments", "new_v1_formatted"];
 pub const FMT_ARGUMENTV1_NEW: [&str; 4] = ["core", "fmt", "ArgumentV1", "new"];
+pub const FN: [&str; 3] = ["core", "ops", "Fn"];
+pub const FN_MUT: [&str; 3] = ["core", "ops", "FnMut"];
+pub const FN_ONCE: [&str; 3] = ["core", "ops", "FnOnce"];
 pub const FROM_FROM: [&str; 4] = ["core", "convert", "From", "from"];
 pub const FROM_TRAIT: [&str; 3] = ["core", "convert", "From"];
 pub const FUTURE_FROM_GENERATOR: [&str; 3] = ["core", "future", "from_generator"];
index 913cd004f19f4bd70941f49127930ec902573669..bc725a645acf9a21b7df532485ecdff3bdac7bf2 100644 (file)
@@ -259,4 +259,36 @@ fn needless_lt<'a>(_x: &'a u8) {}
     }
 }
 
+mod nested_elision_sites {
+    // Don't lint these cases, they cause FPs.
+    // The lint does not support nested elision sites.
+
+    fn nested_fn_trait_bound<'a>(i: &'a i32) -> impl Fn() -> &'a i32 {
+        move || i
+    }
+
+    fn nested_fn_mut_trait_bound<'a>(i: &'a i32) -> impl FnMut() -> &'a i32 {
+        move || i
+    }
+
+    fn nested_fn_once_trait_bound<'a>(i: &'a i32) -> impl FnOnce() -> &'a i32 {
+        move || i
+    }
+
+    fn nested_generic_fn_trait_bound<'a, T: Fn() -> &'a i32>(f: T) -> &'a i32 {
+        f()
+    }
+
+    fn nested_where_clause_fn_trait_bound<'a, T>(f: T) -> &'a i32
+    where
+        T: Fn() -> &'a i32,
+    {
+        f()
+    }
+
+    fn nested_pointer_fn<'a>(_: &'a i32) -> fn(&'a i32) -> &'a i32 {
+        |i| i
+    }
+}
+
 fn main() {}
index d3a360ed8b576d04bf95e0327c1854f81ad8fb4a..b1943bf9d703ca3851734ab9f4584a6b8505f1cd 100644 (file)
@@ -36,12 +36,6 @@ error: explicit lifetimes given in parameter types where they could be elided (o
 LL | fn lifetime_param_2<'a, 'b>(_x: Ref<'a>, _y: &'b u8) {}
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-error: explicit lifetimes given in parameter types where they could be elided (or replaced with `'_` if needed by type declaration)
-  --> $DIR/needless_lifetimes.rs:86:1
-   |
-LL | fn fn_bound_2<'a, F, I>(_m: Lt<'a, I>, _f: F) -> Lt<'a, I>
-   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
 error: explicit lifetimes given in parameter types where they could be elided (or replaced with `'_` if needed by type declaration)
   --> $DIR/needless_lifetimes.rs:120:5
    |
@@ -102,5 +96,5 @@ error: explicit lifetimes given in parameter types where they could be elided (o
 LL |         fn needless_lt<'a>(_x: &'a u8) {}
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-error: aborting due to 17 previous errors
+error: aborting due to 16 previous errors