1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::ty::same_type_and_consts;
3 use clippy_utils::{in_macro, meets_msrv, msrvs};
4 use if_chain::if_chain;
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_errors::Applicability;
9 def::{CtorOf, DefKind, Res},
11 intravisit::{walk_inf, walk_ty, NestedVisitorMap, Visitor},
12 Expr, ExprKind, FnRetTy, FnSig, GenericArg, HirId, Impl, ImplItemKind, Item, ItemKind, Path, QPath, TyKind,
14 use rustc_lint::{LateContext, LateLintPass, LintContext};
15 use rustc_middle::hir::map::Map;
16 use rustc_middle::ty::AssocKind;
17 use rustc_semver::RustcVersion;
18 use rustc_session::{declare_tool_lint, impl_lint_pass};
20 use rustc_typeck::hir_ty_to_ty;
22 declare_clippy_lint! {
24 /// Checks for unnecessary repetition of structure name when a
25 /// replacement with `Self` is applicable.
27 /// ### Why is this bad?
28 /// Unnecessary repetition. Mixed use of `Self` and struct
30 /// feels inconsistent.
32 /// ### Known problems
33 /// - Unaddressed false negative in fn bodies of trait implementations
34 /// - False positive with assotiated types in traits (#4140)
49 /// fn new() -> Self {
56 "unnecessary structure name repetition whereas `Self` is applicable"
61 msrv: Option<RustcVersion>,
62 stack: Vec<StackItem>,
67 pub fn new(msrv: Option<RustcVersion>) -> Self {
80 types_to_skip: FxHashSet<HirId>,
85 impl_lint_pass!(UseSelf => [USE_SELF]);
87 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
89 impl<'tcx> LateLintPass<'tcx> for UseSelf {
90 fn check_item(&mut self, _cx: &LateContext<'_>, item: &Item<'_>) {
91 if matches!(item.kind, ItemKind::OpaqueTy(_)) {
92 // skip over `ItemKind::OpaqueTy` in order to lint `foo() -> impl <..>`
95 // We push the self types of `impl`s on a stack here. Only the top type on the stack is
96 // relevant for linting, since this is the self type of the `impl` we're currently in. To
97 // avoid linting on nested items, we push `StackItem::NoCheck` on the stack to signal, that
98 // we're in an `impl` or nested item, that we don't want to lint
99 let stack_item = if_chain! {
100 if let ItemKind::Impl(Impl { self_ty, .. }) = item.kind;
101 if let TyKind::Path(QPath::Resolved(_, item_path)) = self_ty.kind;
102 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
103 if parameters.as_ref().map_or(true, |params| {
104 !params.parenthesized && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
108 impl_id: item.def_id,
110 types_to_skip: std::iter::once(self_ty.hir_id).collect(),
116 self.stack.push(stack_item);
119 fn check_item_post(&mut self, _: &LateContext<'_>, item: &Item<'_>) {
120 if !matches!(item.kind, ItemKind::OpaqueTy(_)) {
125 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
126 // We want to skip types in trait `impl`s that aren't declared as `Self` in the trait
127 // declaration. The collection of those types is all this method implementation does.
129 if let ImplItemKind::Fn(FnSig { decl, .. }, ..) = impl_item.kind;
130 if let Some(&mut StackItem::Check {
132 ref mut types_to_skip,
134 }) = self.stack.last_mut();
135 if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_id);
137 // `self_ty` is the semantic self type of `impl <trait> for <type>`. This cannot be
139 let self_ty = impl_trait_ref.self_ty();
141 // `trait_method_sig` is the signature of the function, how it is declared in the
142 // trait, not in the impl of the trait.
143 let trait_method = cx
145 .associated_items(impl_trait_ref.def_id)
146 .find_by_name_and_kind(cx.tcx, impl_item.ident, AssocKind::Fn, impl_trait_ref.def_id)
147 .expect("impl method matches a trait method");
148 let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
149 let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig);
151 // `impl_inputs_outputs` is an iterator over the types (`hir::Ty`) declared in the
152 // implementation of the trait.
153 let output_hir_ty = if let FnRetTy::Return(ty) = &decl.output {
158 let impl_inputs_outputs = decl.inputs.iter().chain(output_hir_ty);
160 // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature.
162 // `trait_sem_ty` (of type `ty::Ty`) is the semantic type for the signature in the
163 // trait declaration. This is used to check if `Self` was used in the trait
166 // If `any`where in the `trait_sem_ty` the `self_ty` was used verbatim (as opposed
167 // to `Self`), we want to skip linting that type and all subtypes of it. This
168 // avoids suggestions to e.g. replace `Vec<u8>` with `Vec<Self>`, in an `impl Trait
169 // for u8`, when the trait always uses `Vec<u8>`.
171 // See also https://github.com/rust-lang/rust-clippy/issues/2894.
172 for (impl_hir_ty, trait_sem_ty) in impl_inputs_outputs.zip(trait_method_sig.inputs_and_output) {
173 if trait_sem_ty.walk(cx.tcx).any(|inner| inner == self_ty.into()) {
174 let mut visitor = SkipTyCollector::default();
175 visitor.visit_ty(impl_hir_ty);
176 types_to_skip.extend(visitor.types_to_skip);
183 fn check_body(&mut self, _: &LateContext<'_>, _: &hir::Body<'_>) {
184 // `hir_ty_to_ty` cannot be called in `Body`s or it will panic (sometimes). But in bodies
185 // we can use `cx.typeck_results.node_type(..)` to get the `ty::Ty` from a `hir::Ty`.
186 // However the `node_type()` method can *only* be called in bodies.
187 if let Some(&mut StackItem::Check { ref mut in_body, .. }) = self.stack.last_mut() {
188 *in_body = in_body.saturating_add(1);
192 fn check_body_post(&mut self, _: &LateContext<'_>, _: &hir::Body<'_>) {
193 if let Some(&mut StackItem::Check { ref mut in_body, .. }) = self.stack.last_mut() {
194 *in_body = in_body.saturating_sub(1);
198 fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
200 if !in_macro(hir_ty.span);
201 if meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS);
202 if let Some(&StackItem::Check {
206 }) = self.stack.last();
207 if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind;
208 if !matches!(path.res, Res::SelfTy(..) | Res::Def(DefKind::TyParam, _));
209 if !types_to_skip.contains(&hir_ty.hir_id);
210 let ty = if in_body > 0 {
211 cx.typeck_results().node_type(hir_ty.hir_id)
213 hir_ty_to_ty(cx.tcx, hir_ty)
215 if same_type_and_consts(ty, cx.tcx.type_of(impl_id));
216 let hir = cx.tcx.hir();
217 let id = hir.get_parent_node(hir_ty.hir_id);
218 if !hir.opt_span(id).map_or(false, in_macro);
220 span_lint(cx, hir_ty.span);
225 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
227 if !in_macro(expr.span);
228 if meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS);
229 if let Some(&StackItem::Check { impl_id, .. }) = self.stack.last();
230 if cx.typeck_results().expr_ty(expr) == cx.tcx.type_of(impl_id);
231 then {} else { return; }
234 ExprKind::Struct(QPath::Resolved(_, path), ..) => match path.res {
235 Res::SelfTy(..) => (),
236 Res::Def(DefKind::Variant, _) => lint_path_to_variant(cx, path),
237 _ => span_lint(cx, path.span),
239 // tuple struct instantiation (`Foo(arg)` or `Enum::Foo(arg)`)
240 ExprKind::Call(fun, _) => {
241 if let ExprKind::Path(QPath::Resolved(_, path)) = fun.kind {
242 if let Res::Def(DefKind::Ctor(ctor_of, _), ..) = path.res {
244 CtorOf::Variant => lint_path_to_variant(cx, path),
245 CtorOf::Struct => span_lint(cx, path.span),
250 // unit enum variants (`Enum::A`)
251 ExprKind::Path(QPath::Resolved(_, path)) => lint_path_to_variant(cx, path),
256 extract_msrv_attr!(LateContext);
260 struct SkipTyCollector {
261 types_to_skip: Vec<HirId>,
264 impl<'tcx> Visitor<'tcx> for SkipTyCollector {
265 type Map = Map<'tcx>;
267 fn visit_infer(&mut self, inf: &hir::InferArg) {
268 self.types_to_skip.push(inf.hir_id);
272 fn visit_ty(&mut self, hir_ty: &hir::Ty<'_>) {
273 self.types_to_skip.push(hir_ty.hir_id);
275 walk_ty(self, hir_ty);
278 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
279 NestedVisitorMap::None
283 fn span_lint(cx: &LateContext<'_>, span: Span) {
288 "unnecessary structure name repetition",
289 "use the applicable keyword",
291 Applicability::MachineApplicable,
295 fn lint_path_to_variant(cx: &LateContext<'_>, path: &Path<'_>) {
296 if let [.., self_seg, _variant] = path.segments {
299 .with_hi(self_seg.args().span_ext().unwrap_or(self_seg.ident.span).hi());