]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/use_self.rs
Auto merge of #86662 - mockersf:fix-86620-link-unknown-location, r=jyn514
[rust.git] / src / tools / clippy / clippy_lints / src / use_self.rs
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;
7 use rustc_hir::{
8     self as hir,
9     def::{CtorOf, DefKind, Res},
10     def_id::LocalDefId,
11     intravisit::{walk_ty, NestedVisitorMap, Visitor},
12     Expr, ExprKind, FnRetTy, FnSig, GenericArg, HirId, Impl, ImplItemKind, Item, ItemKind, Path, QPath, TyKind,
13 };
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};
19 use rustc_span::Span;
20 use rustc_typeck::hir_ty_to_ty;
21
22 declare_clippy_lint! {
23     /// **What it does:** Checks for unnecessary repetition of structure name when a
24     /// replacement with `Self` is applicable.
25     ///
26     /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
27     /// name
28     /// feels inconsistent.
29     ///
30     /// **Known problems:**
31     /// - Unaddressed false negative in fn bodies of trait implementations
32     /// - False positive with assotiated types in traits (#4140)
33     ///
34     /// **Example:**
35     ///
36     /// ```rust
37     /// struct Foo {}
38     /// impl Foo {
39     ///     fn new() -> Foo {
40     ///         Foo {}
41     ///     }
42     /// }
43     /// ```
44     /// could be
45     /// ```rust
46     /// struct Foo {}
47     /// impl Foo {
48     ///     fn new() -> Self {
49     ///         Self {}
50     ///     }
51     /// }
52     /// ```
53     pub USE_SELF,
54     nursery,
55     "unnecessary structure name repetition whereas `Self` is applicable"
56 }
57
58 #[derive(Default)]
59 pub struct UseSelf {
60     msrv: Option<RustcVersion>,
61     stack: Vec<StackItem>,
62 }
63
64 impl UseSelf {
65     #[must_use]
66     pub fn new(msrv: Option<RustcVersion>) -> Self {
67         Self {
68             msrv,
69             ..Self::default()
70         }
71     }
72 }
73
74 #[derive(Debug)]
75 enum StackItem {
76     Check {
77         impl_id: LocalDefId,
78         in_body: u32,
79         types_to_skip: FxHashSet<HirId>,
80     },
81     NoCheck,
82 }
83
84 impl_lint_pass!(UseSelf => [USE_SELF]);
85
86 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
87
88 impl<'tcx> LateLintPass<'tcx> for UseSelf {
89     fn check_item(&mut self, _cx: &LateContext<'_>, item: &Item<'_>) {
90         if matches!(item.kind, ItemKind::OpaqueTy(_)) {
91             // skip over `ItemKind::OpaqueTy` in order to lint `foo() -> impl <..>`
92             return;
93         }
94         // We push the self types of `impl`s on a stack here. Only the top type on the stack is
95         // relevant for linting, since this is the self type of the `impl` we're currently in. To
96         // avoid linting on nested items, we push `StackItem::NoCheck` on the stack to signal, that
97         // we're in an `impl` or nested item, that we don't want to lint
98         let stack_item = if_chain! {
99             if let ItemKind::Impl(Impl { self_ty, .. }) = item.kind;
100             if let TyKind::Path(QPath::Resolved(_, item_path)) = self_ty.kind;
101             let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
102             if parameters.as_ref().map_or(true, |params| {
103                 !params.parenthesized && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
104             });
105             then {
106                 StackItem::Check {
107                     impl_id: item.def_id,
108                     in_body: 0,
109                     types_to_skip: std::iter::once(self_ty.hir_id).collect(),
110                 }
111             } else {
112                 StackItem::NoCheck
113             }
114         };
115         self.stack.push(stack_item);
116     }
117
118     fn check_item_post(&mut self, _: &LateContext<'_>, item: &Item<'_>) {
119         if !matches!(item.kind, ItemKind::OpaqueTy(_)) {
120             self.stack.pop();
121         }
122     }
123
124     fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
125         // We want to skip types in trait `impl`s that aren't declared as `Self` in the trait
126         // declaration. The collection of those types is all this method implementation does.
127         if_chain! {
128             if let ImplItemKind::Fn(FnSig { decl, .. }, ..) = impl_item.kind;
129             if let Some(&mut StackItem::Check {
130                 impl_id,
131                 ref mut types_to_skip,
132                 ..
133             }) = self.stack.last_mut();
134             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_id);
135             then {
136                 // `self_ty` is the semantic self type of `impl <trait> for <type>`. This cannot be
137                 // `Self`.
138                 let self_ty = impl_trait_ref.self_ty();
139
140                 // `trait_method_sig` is the signature of the function, how it is declared in the
141                 // trait, not in the impl of the trait.
142                 let trait_method = cx
143                     .tcx
144                     .associated_items(impl_trait_ref.def_id)
145                     .find_by_name_and_kind(cx.tcx, impl_item.ident, AssocKind::Fn, impl_trait_ref.def_id)
146                     .expect("impl method matches a trait method");
147                 let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
148                 let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig);
149
150                 // `impl_inputs_outputs` is an iterator over the types (`hir::Ty`) declared in the
151                 // implementation of the trait.
152                 let output_hir_ty = if let FnRetTy::Return(ty) = &decl.output {
153                     Some(&**ty)
154                 } else {
155                     None
156                 };
157                 let impl_inputs_outputs = decl.inputs.iter().chain(output_hir_ty);
158
159                 // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature.
160                 //
161                 // `trait_sem_ty` (of type `ty::Ty`) is the semantic type for the signature in the
162                 // trait declaration. This is used to check if `Self` was used in the trait
163                 // declaration.
164                 //
165                 // If `any`where in the `trait_sem_ty` the `self_ty` was used verbatim (as opposed
166                 // to `Self`), we want to skip linting that type and all subtypes of it. This
167                 // avoids suggestions to e.g. replace `Vec<u8>` with `Vec<Self>`, in an `impl Trait
168                 // for u8`, when the trait always uses `Vec<u8>`.
169                 //
170                 // See also https://github.com/rust-lang/rust-clippy/issues/2894.
171                 for (impl_hir_ty, trait_sem_ty) in impl_inputs_outputs.zip(trait_method_sig.inputs_and_output) {
172                     if trait_sem_ty.walk().any(|inner| inner == self_ty.into()) {
173                         let mut visitor = SkipTyCollector::default();
174                         visitor.visit_ty(impl_hir_ty);
175                         types_to_skip.extend(visitor.types_to_skip);
176                     }
177                 }
178             }
179         }
180     }
181
182     fn check_body(&mut self, _: &LateContext<'_>, _: &hir::Body<'_>) {
183         // `hir_ty_to_ty` cannot be called in `Body`s or it will panic (sometimes). But in bodies
184         // we can use `cx.typeck_results.node_type(..)` to get the `ty::Ty` from a `hir::Ty`.
185         // However the `node_type()` method can *only* be called in bodies.
186         if let Some(&mut StackItem::Check { ref mut in_body, .. }) = self.stack.last_mut() {
187             *in_body = in_body.saturating_add(1);
188         }
189     }
190
191     fn check_body_post(&mut self, _: &LateContext<'_>, _: &hir::Body<'_>) {
192         if let Some(&mut StackItem::Check { ref mut in_body, .. }) = self.stack.last_mut() {
193             *in_body = in_body.saturating_sub(1);
194         }
195     }
196
197     fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
198         if_chain! {
199             if !in_macro(hir_ty.span);
200             if meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS);
201             if let Some(&StackItem::Check {
202                 impl_id,
203                 in_body,
204                 ref types_to_skip,
205             }) = self.stack.last();
206             if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind;
207             if !matches!(path.res, Res::SelfTy(..) | Res::Def(DefKind::TyParam, _));
208             if !types_to_skip.contains(&hir_ty.hir_id);
209             let ty = if in_body > 0 {
210                 cx.typeck_results().node_type(hir_ty.hir_id)
211             } else {
212                 hir_ty_to_ty(cx.tcx, hir_ty)
213             };
214             if same_type_and_consts(ty, cx.tcx.type_of(impl_id));
215             let hir = cx.tcx.hir();
216             let id = hir.get_parent_node(hir_ty.hir_id);
217             if !hir.opt_span(id).map_or(false, in_macro);
218             then {
219                 span_lint(cx, hir_ty.span);
220             }
221         }
222     }
223
224     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
225         if_chain! {
226             if !in_macro(expr.span);
227             if meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS);
228             if let Some(&StackItem::Check { impl_id, .. }) = self.stack.last();
229             if cx.typeck_results().expr_ty(expr) == cx.tcx.type_of(impl_id);
230             then {} else { return; }
231         }
232         match expr.kind {
233             ExprKind::Struct(QPath::Resolved(_, path), ..) => match path.res {
234                 Res::SelfTy(..) => (),
235                 Res::Def(DefKind::Variant, _) => lint_path_to_variant(cx, path),
236                 _ => span_lint(cx, path.span),
237             },
238             // tuple struct instantiation (`Foo(arg)` or `Enum::Foo(arg)`)
239             ExprKind::Call(fun, _) => {
240                 if let ExprKind::Path(QPath::Resolved(_, path)) = fun.kind {
241                     if let Res::Def(DefKind::Ctor(ctor_of, _), ..) = path.res {
242                         match ctor_of {
243                             CtorOf::Variant => lint_path_to_variant(cx, path),
244                             CtorOf::Struct => span_lint(cx, path.span),
245                         }
246                     }
247                 }
248             },
249             // unit enum variants (`Enum::A`)
250             ExprKind::Path(QPath::Resolved(_, path)) => lint_path_to_variant(cx, path),
251             _ => (),
252         }
253     }
254
255     extract_msrv_attr!(LateContext);
256 }
257
258 #[derive(Default)]
259 struct SkipTyCollector {
260     types_to_skip: Vec<HirId>,
261 }
262
263 impl<'tcx> Visitor<'tcx> for SkipTyCollector {
264     type Map = Map<'tcx>;
265
266     fn visit_ty(&mut self, hir_ty: &hir::Ty<'_>) {
267         self.types_to_skip.push(hir_ty.hir_id);
268
269         walk_ty(self, hir_ty);
270     }
271
272     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
273         NestedVisitorMap::None
274     }
275 }
276
277 fn span_lint(cx: &LateContext<'_>, span: Span) {
278     span_lint_and_sugg(
279         cx,
280         USE_SELF,
281         span,
282         "unnecessary structure name repetition",
283         "use the applicable keyword",
284         "Self".to_owned(),
285         Applicability::MachineApplicable,
286     );
287 }
288
289 fn lint_path_to_variant(cx: &LateContext<'_>, path: &Path<'_>) {
290     if let [.., self_seg, _variant] = path.segments {
291         let span = path
292             .span
293             .with_hi(self_seg.args().span_ext().unwrap_or(self_seg.ident.span).hi());
294         span_lint(cx, span);
295     }
296 }