diff --git a/clippy_lints/src/use_self.rs b/clippy_lints/src/use_self.rs index 427a1b657731..df67a0a43425 100644 --- a/clippy_lints/src/use_self.rs +++ b/clippy_lints/src/use_self.rs @@ -1,23 +1,24 @@ +use crate::utils; +use crate::utils::snippet_opt; +use crate::utils::span_lint_and_sugg; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; -use rustc_hir::def::{DefKind, Res}; -use rustc_hir::intravisit::{walk_item, walk_path, walk_ty, NestedVisitorMap, Visitor}; +use rustc_hir::def::DefKind; +use rustc_hir::intravisit::{walk_expr, walk_impl_item, walk_ty, NestedVisitorMap, Visitor}; use rustc_hir::{ - def, FnDecl, FnRetTy, FnSig, GenericArg, HirId, ImplItem, ImplItemKind, Item, ItemKind, Path, PathSegment, QPath, - TyKind, + def, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, ImplItem, ImplItemKind, ItemKind, Node, Path, PathSegment, + QPath, TyKind, }; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::hir::map::Map; use rustc_middle::lint::in_external_macro; use rustc_middle::ty; -use rustc_middle::ty::{DefIdTree, Ty}; +use rustc_middle::ty::Ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::symbol::kw; +use rustc_span::{BytePos, Span}; use rustc_typeck::hir_ty_to_ty; -use crate::utils::{differing_macro_contexts, span_lint_and_sugg}; - declare_clippy_lint! { /// **What it does:** Checks for unnecessary repetition of structure name when a /// replacement with `Self` is applicable. @@ -27,8 +28,7 @@ declare_clippy_lint! { /// feels inconsistent. /// /// **Known problems:** - /// - False positive when using associated types (#2843) - /// - False positives in some situations when using generics (#3410) + /// Unaddressed false negatives related to unresolved internal compiler errors. /// /// **Example:** /// ```rust @@ -57,19 +57,7 @@ declare_lint_pass!(UseSelf => [USE_SELF]); const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element"; -fn span_use_self_lint(cx: &LateContext<'_>, path: &Path<'_>, last_segment: Option<&PathSegment<'_>>) { - let last_segment = last_segment.unwrap_or_else(|| path.segments.last().expect(SEGMENTS_MSG)); - - // Path segments only include actual path, no methods or fields. - let last_path_span = last_segment.ident.span; - - if differing_macro_contexts(path.span, last_path_span) { - return; - } - - // Only take path up to the end of last_path_span. - let span = path.span.with_hi(last_path_span.hi()); - +fn span_lint(cx: &LateContext<'_>, span: Span) { span_lint_and_sugg( cx, USE_SELF, @@ -81,189 +69,237 @@ fn span_use_self_lint(cx: &LateContext<'_>, path: &Path<'_>, last_segment: Optio ); } -// FIXME: always use this (more correct) visitor, not just in method signatures. -struct SemanticUseSelfVisitor<'a, 'tcx> { - cx: &'a LateContext<'tcx>, - self_ty: Ty<'tcx>, +#[allow(clippy::cast_possible_truncation)] +fn span_lint_until_last_segment<'tcx>(cx: &LateContext<'tcx>, span: Span, segment: &'tcx PathSegment<'tcx>) { + let sp = span.with_hi(segment.ident.span.lo()); + // remove the trailing :: + let span_without_last_segment = match snippet_opt(cx, sp) { + Some(snippet) => match snippet.rfind("::") { + Some(bidx) => sp.with_hi(sp.lo() + BytePos(bidx as u32)), + None => sp, + }, + None => sp, + }; + span_lint(cx, span_without_last_segment); } -impl<'a, 'tcx> Visitor<'tcx> for SemanticUseSelfVisitor<'a, 'tcx> { - type Map = Map<'tcx>; - - fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'_>) { - if let TyKind::Path(QPath::Resolved(_, path)) = &hir_ty.kind { - match path.res { - def::Res::SelfTy(..) => {}, - _ => { - if hir_ty_to_ty(self.cx.tcx, hir_ty) == self.self_ty { - span_use_self_lint(self.cx, path, None); - } - }, - } - } - - walk_ty(self, hir_ty) +fn span_lint_on_path_until_last_segment<'tcx>(cx: &LateContext<'tcx>, path: &'tcx Path<'tcx>) { + if path.segments.len() > 1 { + span_lint_until_last_segment(cx, path.span, path.segments.last().unwrap()); } +} - fn nested_visit_map(&mut self) -> NestedVisitorMap { - NestedVisitorMap::None +fn span_lint_on_qpath_resolved<'tcx>(cx: &LateContext<'tcx>, qpath: &'tcx QPath<'tcx>, until_last_segment: bool) { + if let QPath::Resolved(_, path) = qpath { + if until_last_segment { + span_lint_on_path_until_last_segment(cx, path); + } else { + span_lint(cx, path.span); + } } } -fn check_trait_method_impl_decl<'tcx>( - cx: &LateContext<'tcx>, - impl_item: &ImplItem<'_>, - impl_decl: &'tcx FnDecl<'_>, - impl_trait_ref: ty::TraitRef<'tcx>, -) { - let trait_method = cx - .tcx - .associated_items(impl_trait_ref.def_id) - .find_by_name_and_kind(cx.tcx, impl_item.ident, ty::AssocKind::Fn, impl_trait_ref.def_id) - .expect("impl method matches a trait method"); +struct BodyVisitor<'a, 'tcx> { + cx: &'a LateContext<'tcx>, + self_ty: Ty<'tcx>, +} - let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id); - let trait_method_sig = cx.tcx.erase_late_bound_regions(&trait_method_sig); +impl<'a, 'tcx> BodyVisitor<'a, 'tcx> { + fn check_trait_method_impl_decl( + &mut self, + impl_item: &ImplItem<'tcx>, + impl_decl: &'tcx FnDecl<'tcx>, + impl_trait_ref: ty::TraitRef<'tcx>, + ) { + let tcx = self.cx.tcx; + let trait_method = tcx + .associated_items(impl_trait_ref.def_id) + .find_by_name_and_kind(tcx, impl_item.ident, ty::AssocKind::Fn, impl_trait_ref.def_id) + .expect("impl method matches a trait method"); - let output_hir_ty = if let FnRetTy::Return(ty) = &impl_decl.output { - Some(&**ty) - } else { - None - }; + let trait_method_sig = tcx.fn_sig(trait_method.def_id); + let trait_method_sig = tcx.erase_late_bound_regions(&trait_method_sig); - // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature. - // `trait_ty` (of type `ty::Ty`) is the semantic type for the signature in the trait. - // We use `impl_hir_ty` to see if the type was written as `Self`, - // `hir_ty_to_ty(...)` to check semantic types of paths, and - // `trait_ty` to determine which parts of the signature in the trait, mention - // the type being implemented verbatim (as opposed to `Self`). - for (impl_hir_ty, trait_ty) in impl_decl - .inputs - .iter() - .chain(output_hir_ty) - .zip(trait_method_sig.inputs_and_output) - { - // Check if the input/output type in the trait method specifies the implemented - // type verbatim, and only suggest `Self` if that isn't the case. - // This avoids suggestions to e.g. replace `Vec` with `Vec`, - // in an `impl Trait for u8`, when the trait always uses `Vec`. - // See also https://github.com/rust-lang/rust-clippy/issues/2894. - let self_ty = impl_trait_ref.self_ty(); - if !trait_ty.walk().any(|inner| inner == self_ty.into()) { - let mut visitor = SemanticUseSelfVisitor { cx, self_ty }; + let output_hir_ty = if let FnRetTy::Return(ty) = &impl_decl.output { + Some(&**ty) + } else { + None + }; - visitor.visit_ty(&impl_hir_ty); + // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature. + // `trait_ty` (of type `ty::Ty`) is the semantic type for the signature in the trait. + // We use `impl_hir_ty` to see if the type was written as `Self`, + // `hir_ty_to_ty(...)` to check semantic types of paths, and + // `trait_ty` to determine which parts of the signature in the trait, mention + // the type being implemented verbatim (as opposed to `Self`). + for (impl_hir_ty, trait_ty) in impl_decl + .inputs + .iter() + .chain(output_hir_ty) + .zip(trait_method_sig.inputs_and_output) + { + // Check if the input/output type in the trait method specifies the implemented + // type verbatim, and only suggest `Self` if that isn't the case. + // This avoids suggestions to e.g. replace `Vec` with `Vec`, + // in an `impl Trait for u8`, when the trait always uses `Vec`. + // See also https://github.com/rust-lang/rust-clippy/issues/2894. + let self_ty = impl_trait_ref.self_ty(); + if !trait_ty.walk().any(|inner| inner == self_ty.into()) { + self.visit_ty(&impl_hir_ty); + } } } } -impl<'tcx> LateLintPass<'tcx> for UseSelf { - fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { - if in_external_macro(cx.sess(), item.span) { - return; - } - if_chain! { - if let ItemKind::Impl{ self_ty: ref item_type, items: refs, .. } = item.kind; - if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.kind; - then { - let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args; - let should_check = parameters.as_ref().map_or( - true, - |params| !params.parenthesized - &&!params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))) - ); +impl<'a, 'tcx> Visitor<'tcx> for BodyVisitor<'a, 'tcx> { + type Map = Map<'tcx>; - if should_check { - let visitor = &mut UseSelfVisitor { - item_path, - cx, - }; - let impl_def_id = cx.tcx.hir().local_def_id(item.hir_id); - let impl_trait_ref = cx.tcx.impl_trait_ref(impl_def_id); + fn nested_visit_map(&mut self) -> NestedVisitorMap { + NestedVisitorMap::OnlyBodies(self.cx.tcx.hir()) + } - if let Some(impl_trait_ref) = impl_trait_ref { - for impl_item_ref in refs { - let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id); - if let ImplItemKind::Fn(FnSig{ decl: impl_decl, .. }, impl_body_id) - = &impl_item.kind { - check_trait_method_impl_decl(cx, impl_item, impl_decl, impl_trait_ref); + fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) { + fn expr_ty_matches<'tcx>(expr: &'tcx Expr<'tcx>, self_ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool { + let def_id = expr.hir_id.owner; + if cx.tcx.has_typeck_results(def_id) { + cx.tcx.typeck(def_id).expr_ty_opt(expr) == Some(self_ty) + } else { + false + } + } + match expr.kind { + ExprKind::Struct(QPath::Resolved(_, path), ..) => { + if expr_ty_matches(expr, self.self_ty, self.cx) { + match path.res { + def::Res::SelfTy(..) => (), + def::Res::Def(DefKind::Variant, _) => span_lint_on_path_until_last_segment(self.cx, path), + _ => { + span_lint(self.cx, path.span); + }, + } + } + }, + // tuple struct instantiation (`Foo(arg)` or `Enum::Foo(arg)`) + ExprKind::Call(fun, _) => { + if let Expr { + kind: ExprKind::Path(ref qpath), + .. + } = fun + { + if expr_ty_matches(expr, self.self_ty, self.cx) { + let res = utils::qpath_res(self.cx, qpath, fun.hir_id); - let body = cx.tcx.hir().body(*impl_body_id); - visitor.visit_body(body); - } else { - visitor.visit_impl_item(impl_item); + if let def::Res::Def(DefKind::Ctor(ctor_of, _), ..) = res { + match ctor_of { + def::CtorOf::Variant => { + span_lint_on_qpath_resolved(self.cx, qpath, true); + }, + def::CtorOf::Struct => { + span_lint_on_qpath_resolved(self.cx, qpath, false); + }, } } - } else { - for impl_item_ref in refs { - let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id); - visitor.visit_impl_item(impl_item); - } } } - } + }, + // unit enum variants (`Enum::A`) + ExprKind::Path(ref qpath) => { + if expr_ty_matches(expr, self.self_ty, self.cx) { + span_lint_on_qpath_resolved(self.cx, qpath, true); + } + }, + _ => (), } + walk_expr(self, expr); } } -struct UseSelfVisitor<'a, 'tcx> { - item_path: &'a Path<'a>, +struct FnSigVisitor<'a, 'tcx> { cx: &'a LateContext<'tcx>, + self_ty: Ty<'tcx>, } -impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> { +impl<'a, 'tcx> Visitor<'tcx> for FnSigVisitor<'a, 'tcx> { type Map = Map<'tcx>; - fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) { - if !path.segments.iter().any(|p| p.ident.span.is_dummy()) { - if path.segments.len() >= 2 { - let last_but_one = &path.segments[path.segments.len() - 2]; - if last_but_one.ident.name != kw::SelfUpper { - let enum_def_id = match path.res { - Res::Def(DefKind::Variant, variant_def_id) => self.cx.tcx.parent(variant_def_id), - Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), ctor_def_id) => { - let variant_def_id = self.cx.tcx.parent(ctor_def_id); - variant_def_id.and_then(|def_id| self.cx.tcx.parent(def_id)) - }, - _ => None, - }; - - if self.item_path.res.opt_def_id() == enum_def_id { - span_use_self_lint(self.cx, path, Some(last_but_one)); - } - } - } + fn nested_visit_map(&mut self) -> NestedVisitorMap { + NestedVisitorMap::None + } - if path.segments.last().expect(SEGMENTS_MSG).ident.name != kw::SelfUpper { - if self.item_path.res == path.res { - span_use_self_lint(self.cx, path, None); - } else if let Res::Def(DefKind::Ctor(def::CtorOf::Struct, _), ctor_def_id) = path.res { - if self.item_path.res.opt_def_id() == self.cx.tcx.parent(ctor_def_id) { - span_use_self_lint(self.cx, path, None); + fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { + if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind { + match path.res { + def::Res::SelfTy(..) => {}, + _ => { + match self.cx.tcx.hir().find(self.cx.tcx.hir().get_parent_node(hir_ty.hir_id)) { + Some(Node::Expr(Expr { + kind: ExprKind::Path(QPath::TypeRelative(_, segment)), + .. + })) => { + if hir_ty_to_ty(self.cx.tcx, hir_ty) == self.self_ty { + // fixme: this span manipulation should not be necessary + // @flip1995 found an ast lowering issue in + // https://github.com/rust-lang/rust/blob/master/src/librustc_ast_lowering/path.rs#l142-l162 + span_lint_until_last_segment(self.cx, hir_ty.span, segment); + } + }, + _ => { + if hir_ty_to_ty(self.cx.tcx, hir_ty) == self.self_ty { + span_lint(self.cx, hir_ty.span) + } + }, } - } + }, } } - walk_path(self, path); + walk_ty(self, hir_ty); } +} - fn visit_item(&mut self, item: &'tcx Item<'_>) { - match item.kind { - ItemKind::Use(..) - | ItemKind::Static(..) - | ItemKind::Enum(..) - | ItemKind::Struct(..) - | ItemKind::Union(..) - | ItemKind::Impl { .. } - | ItemKind::Fn(..) => { - // Don't check statements that shadow `Self` or where `Self` can't be used - }, - _ => walk_item(self, item), +impl<'tcx> LateLintPass<'tcx> for UseSelf { + fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) { + if in_external_macro(cx.sess(), impl_item.span) { + return; } - } - fn nested_visit_map(&mut self) -> NestedVisitorMap { - NestedVisitorMap::All(self.cx.tcx.hir()) + let parent_id = cx.tcx.hir().get_parent_item(impl_item.hir_id); + let imp = cx.tcx.hir().expect_item(parent_id); + + if_chain! { + if let ItemKind::Impl { self_ty: hir_self_ty, .. } = imp.kind; + if let TyKind::Path(QPath::Resolved(_, ref item_path)) = hir_self_ty.kind; + then { + let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args; + let should_check = parameters.as_ref().map_or( + true, + |params| !params.parenthesized + &&!params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))) + ); + + // TODO: don't short-circuit upon lifetime parameters + if should_check { + let self_ty = hir_ty_to_ty(cx.tcx, hir_self_ty); + let body_visitor = &mut BodyVisitor { cx, self_ty }; + let fn_sig_visitor = &mut FnSigVisitor { cx, self_ty }; + + let tcx = cx.tcx; + let impl_def_id = tcx.hir().local_def_id(imp.hir_id); + let impl_trait_ref = tcx.impl_trait_ref(impl_def_id); + if_chain! { + if let Some(impl_trait_ref) = impl_trait_ref; + if let ImplItemKind::Fn(FnSig { decl: impl_decl, .. }, impl_body_id) = &impl_item.kind; + then { + body_visitor.check_trait_method_impl_decl(impl_item, impl_decl, impl_trait_ref); + let body = tcx.hir().body(*impl_body_id); + body_visitor.visit_body(body); + } else { + walk_impl_item(body_visitor, impl_item); + walk_impl_item(fn_sig_visitor, impl_item); + } + } + } + } + } } } diff --git a/tests/ui/use_self.fixed b/tests/ui/use_self.fixed index ebb3aa28daf3..dee39897a4e1 100644 --- a/tests/ui/use_self.fixed +++ b/tests/ui/use_self.fixed @@ -15,13 +15,16 @@ mod use_self { Self {} } fn test() -> Self { - Self::new() + // FIXME: applicable here + Foo::new() } } impl Default for Foo { - fn default() -> Self { - Self::new() + // FIXME: applicable here + fn default() -> Foo { + // FIXME: applicable here + Foo::new() } } } @@ -86,7 +89,11 @@ mod existential { struct Foo; impl Foo { - fn bad(foos: &[Self]) -> impl Iterator { + // FIXME: + // TyKind::Def (used for `impl Trait` types) does not include type parameters yet. + // See documentation in rustc_hir::hir::TyKind. + // The hir tree walk stops at `impl Iterator` level and does not inspect &Foo. + fn bad(foos: &[Self]) -> impl Iterator { foos.iter() } @@ -176,11 +183,22 @@ mod issue3410 { struct B; trait Trait { - fn a(v: T); + fn a(v: T) -> Self; } impl Trait> for Vec { - fn a(_: Vec) {} + fn a(_: Vec) -> Self { + unimplemented!() + } + } + + impl Trait> for Vec + where + T: Trait, + { + fn a(v: Vec) -> Self { + >::a(v).into_iter().map(Trait::a).collect() + } } } @@ -196,8 +214,10 @@ mod rustfix { fn fun_1() {} fn fun_2() { - Self::fun_1(); - Self::A; + // FIXME: applicable here + nested::A::fun_1(); + // FIXME: applicable here + nested::A::A; Self {}; } @@ -218,7 +238,8 @@ mod issue3567 { impl Test for TestStruct { fn test() -> TestStruct { - Self::from_something() + // FIXME: applicable here + TestStruct::from_something() } } } @@ -232,12 +253,14 @@ mod paths_created_by_lowering { const A: usize = 0; const B: usize = 1; - async fn g() -> Self { + // FIXME: applicable here + async fn g() -> S { Self {} } fn f<'a>(&self, p: &'a [u8]) -> &'a [u8] { - &p[Self::A..Self::B] + // FIXME: applicable here twice + &p[S::A..S::B] } } @@ -251,3 +274,194 @@ mod paths_created_by_lowering { } } } + +// reused from #1997 +mod generics { + struct Foo { + value: T, + } + + impl Foo { + // `Self` is applicable here + fn foo(value: T) -> Self { + Self { value } + } + + // `Cannot` use `Self` as a return type as the generic types are different + fn bar(value: i32) -> Foo { + Foo { value } + } + } +} + +mod issue4140 { + pub struct Error { + _from: From, + _too: To, + } + + pub trait From { + type From; + type To; + + fn from(value: T) -> Self; + } + + pub trait TryFrom + where + Self: Sized, + { + type From; + type To; + + fn try_from(value: T) -> Result>; + } + + impl TryFrom for T + where + T: From, + { + type From = Self; + type To = Self; + + fn try_from(value: F) -> Result> { + Ok(From::from(value)) + } + } + + impl From for i64 { + type From = bool; + type To = Self; + + fn from(value: bool) -> Self { + if value { + 100 + } else { + 0 + } + } + } +} + +mod issue2843 { + trait Foo { + type Bar; + } + + impl Foo for usize { + type Bar = u8; + } + + impl Foo for Option { + type Bar = Option; + } +} + +mod issue3859 { + pub struct Foo; + pub struct Bar([usize; 3]); + + impl Foo { + pub const BAR: usize = 3; + + pub fn foo() { + const _X: usize = Foo::BAR; + // const _Y: usize = Self::BAR; + } + } +} + +mod issue4305 { + trait Foo: 'static {} + + struct Bar; + + impl Foo for Bar {} + + impl From for Box { + fn from(t: T) -> Self { + // FIXME: applicable here + Box::new(t) + } + } +} + +mod lint_at_item_level { + struct Foo {} + + #[allow(clippy::use_self)] + impl Foo { + fn new() -> Foo { + Foo {} + } + } + + #[allow(clippy::use_self)] + impl Default for Foo { + fn default() -> Foo { + Foo::new() + } + } +} + +mod lint_at_impl_item_level { + struct Foo {} + + impl Foo { + #[allow(clippy::use_self)] + fn new() -> Foo { + Foo {} + } + } + + impl Default for Foo { + #[allow(clippy::use_self)] + fn default() -> Foo { + Foo::new() + } + } +} + +mod issue4734 { + #[repr(C, packed)] + pub struct X { + pub x: u32, + } + + impl From for u32 { + fn from(c: X) -> Self { + unsafe { core::mem::transmute(c) } + } + } +} + +mod nested_paths { + use std::convert::Into; + mod submod { + pub struct B {} + pub struct C {} + + impl Into for B { + fn into(self) -> C { + C {} + } + } + } + + struct A { + t: T, + } + + impl A { + fn new>(v: V) -> Self { + Self { t: Into::into(v) } + } + } + + impl A { + fn test() -> Self { + // FIXME: applicable here + A::new::(submod::B {}) + } + } +} diff --git a/tests/ui/use_self.rs b/tests/ui/use_self.rs index 8a182192ab34..60c1c39424f1 100644 --- a/tests/ui/use_self.rs +++ b/tests/ui/use_self.rs @@ -15,12 +15,15 @@ mod use_self { Foo {} } fn test() -> Foo { + // FIXME: applicable here Foo::new() } } impl Default for Foo { + // FIXME: applicable here fn default() -> Foo { + // FIXME: applicable here Foo::new() } } @@ -86,7 +89,11 @@ mod existential { struct Foo; impl Foo { - fn bad(foos: &[Self]) -> impl Iterator { + // FIXME: + // TyKind::Def (used for `impl Trait` types) does not include type parameters yet. + // See documentation in rustc_hir::hir::TyKind. + // The hir tree walk stops at `impl Iterator` level and does not inspect &Foo. + fn bad(foos: &[Foo]) -> impl Iterator { foos.iter() } @@ -176,11 +183,22 @@ mod issue3410 { struct B; trait Trait { - fn a(v: T); + fn a(v: T) -> Self; } impl Trait> for Vec { - fn a(_: Vec) {} + fn a(_: Vec) -> Self { + unimplemented!() + } + } + + impl Trait> for Vec + where + T: Trait, + { + fn a(v: Vec) -> Self { + >::a(v).into_iter().map(Trait::a).collect() + } } } @@ -196,7 +214,9 @@ mod rustfix { fn fun_1() {} fn fun_2() { + // FIXME: applicable here nested::A::fun_1(); + // FIXME: applicable here nested::A::A; nested::A {}; @@ -218,6 +238,7 @@ mod issue3567 { impl Test for TestStruct { fn test() -> TestStruct { + // FIXME: applicable here TestStruct::from_something() } } @@ -232,11 +253,13 @@ mod paths_created_by_lowering { const A: usize = 0; const B: usize = 1; + // FIXME: applicable here async fn g() -> S { S {} } fn f<'a>(&self, p: &'a [u8]) -> &'a [u8] { + // FIXME: applicable here twice &p[S::A..S::B] } } @@ -251,3 +274,194 @@ mod paths_created_by_lowering { } } } + +// reused from #1997 +mod generics { + struct Foo { + value: T, + } + + impl Foo { + // `Self` is applicable here + fn foo(value: T) -> Foo { + Foo { value } + } + + // `Cannot` use `Self` as a return type as the generic types are different + fn bar(value: i32) -> Foo { + Foo { value } + } + } +} + +mod issue4140 { + pub struct Error { + _from: From, + _too: To, + } + + pub trait From { + type From; + type To; + + fn from(value: T) -> Self; + } + + pub trait TryFrom + where + Self: Sized, + { + type From; + type To; + + fn try_from(value: T) -> Result>; + } + + impl TryFrom for T + where + T: From, + { + type From = T::From; + type To = T::To; + + fn try_from(value: F) -> Result> { + Ok(From::from(value)) + } + } + + impl From for i64 { + type From = bool; + type To = Self; + + fn from(value: bool) -> Self { + if value { + 100 + } else { + 0 + } + } + } +} + +mod issue2843 { + trait Foo { + type Bar; + } + + impl Foo for usize { + type Bar = u8; + } + + impl Foo for Option { + type Bar = Option; + } +} + +mod issue3859 { + pub struct Foo; + pub struct Bar([usize; 3]); + + impl Foo { + pub const BAR: usize = 3; + + pub fn foo() { + const _X: usize = Foo::BAR; + // const _Y: usize = Self::BAR; + } + } +} + +mod issue4305 { + trait Foo: 'static {} + + struct Bar; + + impl Foo for Bar {} + + impl From for Box { + fn from(t: T) -> Self { + // FIXME: applicable here + Box::new(t) + } + } +} + +mod lint_at_item_level { + struct Foo {} + + #[allow(clippy::use_self)] + impl Foo { + fn new() -> Foo { + Foo {} + } + } + + #[allow(clippy::use_self)] + impl Default for Foo { + fn default() -> Foo { + Foo::new() + } + } +} + +mod lint_at_impl_item_level { + struct Foo {} + + impl Foo { + #[allow(clippy::use_self)] + fn new() -> Foo { + Foo {} + } + } + + impl Default for Foo { + #[allow(clippy::use_self)] + fn default() -> Foo { + Foo::new() + } + } +} + +mod issue4734 { + #[repr(C, packed)] + pub struct X { + pub x: u32, + } + + impl From for u32 { + fn from(c: X) -> Self { + unsafe { core::mem::transmute(c) } + } + } +} + +mod nested_paths { + use std::convert::Into; + mod submod { + pub struct B {} + pub struct C {} + + impl Into for B { + fn into(self) -> C { + C {} + } + } + } + + struct A { + t: T, + } + + impl A { + fn new>(v: V) -> Self { + Self { t: Into::into(v) } + } + } + + impl A { + fn test() -> Self { + // FIXME: applicable here + A::new::(submod::B {}) + } + } +} diff --git a/tests/ui/use_self.stderr b/tests/ui/use_self.stderr index b33928597c14..4d213316cf53 100644 --- a/tests/ui/use_self.stderr +++ b/tests/ui/use_self.stderr @@ -1,16 +1,16 @@ error: unnecessary structure name repetition - --> $DIR/use_self.rs:14:21 + --> $DIR/use_self.rs:15:13 | -LL | fn new() -> Foo { - | ^^^ help: use the applicable keyword: `Self` +LL | Foo {} + | ^^^ help: use the applicable keyword: `Self` | = note: `-D clippy::use-self` implied by `-D warnings` error: unnecessary structure name repetition - --> $DIR/use_self.rs:15:13 + --> $DIR/use_self.rs:14:21 | -LL | Foo {} - | ^^^ help: use the applicable keyword: `Self` +LL | fn new() -> Foo { + | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition --> $DIR/use_self.rs:17:22 @@ -19,40 +19,22 @@ LL | fn test() -> Foo { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:18:13 + --> $DIR/use_self.rs:96:24 | -LL | Foo::new() - | ^^^ help: use the applicable keyword: `Self` +LL | fn bad(foos: &[Foo]) -> impl Iterator { + | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:23:25 - | -LL | fn default() -> Foo { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self.rs:24:13 - | -LL | Foo::new() - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self.rs:89:56 - | -LL | fn bad(foos: &[Self]) -> impl Iterator { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self.rs:104:13 + --> $DIR/use_self.rs:111:13 | LL | TS(0) | ^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:112:25 + --> $DIR/use_self.rs:120:17 | -LL | fn new() -> Foo { - | ^^^ help: use the applicable keyword: `Self` +LL | Foo {} + | ^^^ help: use the applicable keyword: `Self` ... LL | use_self_expand!(); // Should lint in local macros | ------------------- in this macro invocation @@ -60,10 +42,10 @@ LL | use_self_expand!(); // Should lint in local macros = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: unnecessary structure name repetition - --> $DIR/use_self.rs:113:17 + --> $DIR/use_self.rs:119:25 | -LL | Foo {} - | ^^^ help: use the applicable keyword: `Self` +LL | fn new() -> Foo { + | ^^^ help: use the applicable keyword: `Self` ... LL | use_self_expand!(); // Should lint in local macros | ------------------- in this macro invocation @@ -71,94 +53,82 @@ LL | use_self_expand!(); // Should lint in local macros = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: unnecessary structure name repetition - --> $DIR/use_self.rs:148:21 + --> $DIR/use_self.rs:144:21 | -LL | fn baz() -> Foo { +LL | Bar { foo: Foo {} } | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:149:13 + --> $DIR/use_self.rs:143:29 | -LL | Foo {} - | ^^^ help: use the applicable keyword: `Self` +LL | fn bar() -> Bar { + | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:136:29 + --> $DIR/use_self.rs:156:13 | -LL | fn bar() -> Bar { - | ^^^ help: use the applicable keyword: `Self` +LL | Foo {} + | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:137:21 + --> $DIR/use_self.rs:155:21 | -LL | Bar { foo: Foo {} } +LL | fn baz() -> Foo { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:166:21 + --> $DIR/use_self.rs:173:21 | LL | let _ = Enum::B(42); | ^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:167:21 + --> $DIR/use_self.rs:174:21 | LL | let _ = Enum::C { field: true }; | ^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:168:21 + --> $DIR/use_self.rs:175:21 | LL | let _ = Enum::A; | ^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:199:13 - | -LL | nested::A::fun_1(); - | ^^^^^^^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self.rs:200:13 - | -LL | nested::A::A; - | ^^^^^^^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self.rs:202:13 + --> $DIR/use_self.rs:222:13 | LL | nested::A {}; | ^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:221:13 + --> $DIR/use_self.rs:258:13 | -LL | TestStruct::from_something() - | ^^^^^^^^^^ help: use the applicable keyword: `Self` +LL | S {} + | ^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:235:25 + --> $DIR/use_self.rs:287:13 | -LL | async fn g() -> S { - | ^ help: use the applicable keyword: `Self` +LL | Foo { value } + | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:236:13 + --> $DIR/use_self.rs:286:29 | -LL | S {} - | ^ help: use the applicable keyword: `Self` +LL | fn foo(value: T) -> Foo { + | ^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:240:16 + --> $DIR/use_self.rs:324:21 | -LL | &p[S::A..S::B] - | ^ help: use the applicable keyword: `Self` +LL | type From = T::From; + | ^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> $DIR/use_self.rs:240:22 + --> $DIR/use_self.rs:325:19 | -LL | &p[S::A..S::B] - | ^ help: use the applicable keyword: `Self` +LL | type To = T::To; + | ^^^^^ help: use the applicable keyword: `Self` -error: aborting due to 25 previous errors +error: aborting due to 20 previous errors diff --git a/tests/ui/use_self_trait.fixed b/tests/ui/use_self_trait.fixed index 1582ae114bf4..680a0623839e 100644 --- a/tests/ui/use_self_trait.fixed +++ b/tests/ui/use_self_trait.fixed @@ -18,36 +18,36 @@ trait SelfTrait { struct Bad; impl SelfTrait for Bad { - fn refs(p1: &Self) -> &Self { + fn refs(p1: &Bad) -> &Bad { p1 } - fn ref_refs<'a>(p1: &'a &'a Self) -> &'a &'a Self { + fn ref_refs<'a>(p1: &'a &'a Bad) -> &'a &'a Bad { p1 } - fn mut_refs(p1: &mut Self) -> &mut Self { + fn mut_refs(p1: &mut Bad) -> &mut Bad { p1 } - fn nested(_p1: Box, _p2: (&u8, &Self)) {} + fn nested(_p1: Box, _p2: (&u8, &Bad)) {} - fn vals(_: Self) -> Self { - Self::default() + fn vals(_: Bad) -> Bad { + Bad::default() } } impl Mul for Bad { type Output = Self; - fn mul(self, rhs: Self) -> Self { + fn mul(self, rhs: Bad) -> Bad { rhs } } impl Clone for Bad { fn clone(&self) -> Self { - Self + Bad } } diff --git a/tests/ui/use_self_trait.stderr b/tests/ui/use_self_trait.stderr index 4f2506cc1192..5409ccedf859 100644 --- a/tests/ui/use_self_trait.stderr +++ b/tests/ui/use_self_trait.stderr @@ -1,94 +1,10 @@ -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:21:18 - | -LL | fn refs(p1: &Bad) -> &Bad { - | ^^^ help: use the applicable keyword: `Self` - | - = note: `-D clippy::use-self` implied by `-D warnings` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:21:27 - | -LL | fn refs(p1: &Bad) -> &Bad { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:25:33 - | -LL | fn ref_refs<'a>(p1: &'a &'a Bad) -> &'a &'a Bad { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:25:49 - | -LL | fn ref_refs<'a>(p1: &'a &'a Bad) -> &'a &'a Bad { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:29:26 - | -LL | fn mut_refs(p1: &mut Bad) -> &mut Bad { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:29:39 - | -LL | fn mut_refs(p1: &mut Bad) -> &mut Bad { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:33:24 - | -LL | fn nested(_p1: Box, _p2: (&u8, &Bad)) {} - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:33:42 - | -LL | fn nested(_p1: Box, _p2: (&u8, &Bad)) {} - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:35:16 - | -LL | fn vals(_: Bad) -> Bad { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:35:24 - | -LL | fn vals(_: Bad) -> Bad { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:36:9 - | -LL | Bad::default() - | ^^^ help: use the applicable keyword: `Self` - error: unnecessary structure name repetition --> $DIR/use_self_trait.rs:41:19 | LL | type Output = Bad; | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:43:23 | -LL | fn mul(self, rhs: Bad) -> Bad { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:43:31 - | -LL | fn mul(self, rhs: Bad) -> Bad { - | ^^^ help: use the applicable keyword: `Self` - -error: unnecessary structure name repetition - --> $DIR/use_self_trait.rs:50:9 - | -LL | Bad - | ^^^ help: use the applicable keyword: `Self` + = note: `-D clippy::use-self` implied by `-D warnings` -error: aborting due to 15 previous errors +error: aborting due to previous error