]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/use_self.rs
Rollup merge of #86714 - iwahbe:add-linked-list-cursor-end-methods, r=Amanieu
[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 !is_item_interesting(item) {
91             // This does two things:
92             //  1) Reduce needless churn on `self.stack`
93             //  2) Don't push `StackItem::NoCheck` when entering `ItemKind::OpaqueTy`,
94             //     in order to lint `foo() -> impl <..>`
95             return;
96         }
97         // We push the self types of `impl`s on a stack here. Only the top type on the stack is
98         // relevant for linting, since this is the self type of the `impl` we're currently in. To
99         // avoid linting on nested items, we push `StackItem::NoCheck` on the stack to signal, that
100         // we're in an `impl` or nested item, that we don't want to lint
101         let stack_item = if_chain! {
102             if let ItemKind::Impl(Impl { self_ty, .. }) = item.kind;
103             if let TyKind::Path(QPath::Resolved(_, item_path)) = self_ty.kind;
104             let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
105             if parameters.as_ref().map_or(true, |params| {
106                 !params.parenthesized && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
107             });
108             then {
109                 StackItem::Check {
110                     impl_id: item.def_id,
111                     in_body: 0,
112                     types_to_skip: std::iter::once(self_ty.hir_id).collect(),
113                 }
114             } else {
115                 StackItem::NoCheck
116             }
117         };
118         self.stack.push(stack_item);
119     }
120
121     fn check_item_post(&mut self, _: &LateContext<'_>, item: &Item<'_>) {
122         if is_item_interesting(item) {
123             self.stack.pop();
124         }
125     }
126
127     fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
128         // We want to skip types in trait `impl`s that aren't declared as `Self` in the trait
129         // declaration. The collection of those types is all this method implementation does.
130         if_chain! {
131             if let ImplItemKind::Fn(FnSig { decl, .. }, ..) = impl_item.kind;
132             if let Some(&mut StackItem::Check {
133                 impl_id,
134                 ref mut types_to_skip,
135                 ..
136             }) = self.stack.last_mut();
137             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_id);
138             then {
139                 // `self_ty` is the semantic self type of `impl <trait> for <type>`. This cannot be
140                 // `Self`.
141                 let self_ty = impl_trait_ref.self_ty();
142
143                 // `trait_method_sig` is the signature of the function, how it is declared in the
144                 // trait, not in the impl of the trait.
145                 let trait_method = cx
146                     .tcx
147                     .associated_items(impl_trait_ref.def_id)
148                     .find_by_name_and_kind(cx.tcx, impl_item.ident, AssocKind::Fn, impl_trait_ref.def_id)
149                     .expect("impl method matches a trait method");
150                 let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
151                 let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig);
152
153                 // `impl_inputs_outputs` is an iterator over the types (`hir::Ty`) declared in the
154                 // implementation of the trait.
155                 let output_hir_ty = if let FnRetTy::Return(ty) = &decl.output {
156                     Some(&**ty)
157                 } else {
158                     None
159                 };
160                 let impl_inputs_outputs = decl.inputs.iter().chain(output_hir_ty);
161
162                 // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature.
163                 //
164                 // `trait_sem_ty` (of type `ty::Ty`) is the semantic type for the signature in the
165                 // trait declaration. This is used to check if `Self` was used in the trait
166                 // declaration.
167                 //
168                 // If `any`where in the `trait_sem_ty` the `self_ty` was used verbatim (as opposed
169                 // to `Self`), we want to skip linting that type and all subtypes of it. This
170                 // avoids suggestions to e.g. replace `Vec<u8>` with `Vec<Self>`, in an `impl Trait
171                 // for u8`, when the trait always uses `Vec<u8>`.
172                 //
173                 // See also https://github.com/rust-lang/rust-clippy/issues/2894.
174                 for (impl_hir_ty, trait_sem_ty) in impl_inputs_outputs.zip(trait_method_sig.inputs_and_output) {
175                     if trait_sem_ty.walk().any(|inner| inner == self_ty.into()) {
176                         let mut visitor = SkipTyCollector::default();
177                         visitor.visit_ty(impl_hir_ty);
178                         types_to_skip.extend(visitor.types_to_skip);
179                     }
180                 }
181             }
182         }
183     }
184
185     fn check_body(&mut self, _: &LateContext<'_>, _: &hir::Body<'_>) {
186         // `hir_ty_to_ty` cannot be called in `Body`s or it will panic (sometimes). But in bodies
187         // we can use `cx.typeck_results.node_type(..)` to get the `ty::Ty` from a `hir::Ty`.
188         // However the `node_type()` method can *only* be called in bodies.
189         if let Some(&mut StackItem::Check { ref mut in_body, .. }) = self.stack.last_mut() {
190             *in_body = in_body.saturating_add(1);
191         }
192     }
193
194     fn check_body_post(&mut self, _: &LateContext<'_>, _: &hir::Body<'_>) {
195         if let Some(&mut StackItem::Check { ref mut in_body, .. }) = self.stack.last_mut() {
196             *in_body = in_body.saturating_sub(1);
197         }
198     }
199
200     fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
201         if_chain! {
202             if !in_macro(hir_ty.span);
203             if meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS);
204             if let Some(&StackItem::Check {
205                 impl_id,
206                 in_body,
207                 ref types_to_skip,
208             }) = self.stack.last();
209             if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind;
210             if !matches!(path.res, Res::SelfTy(..) | Res::Def(DefKind::TyParam, _));
211             if !types_to_skip.contains(&hir_ty.hir_id);
212             let ty = if in_body > 0 {
213                 cx.typeck_results().node_type(hir_ty.hir_id)
214             } else {
215                 hir_ty_to_ty(cx.tcx, hir_ty)
216             };
217             if same_type_and_consts(ty, cx.tcx.type_of(impl_id));
218             let hir = cx.tcx.hir();
219             let id = hir.get_parent_node(hir_ty.hir_id);
220             if !hir.opt_span(id).map_or(false, in_macro);
221             then {
222                 span_lint(cx, hir_ty.span);
223             }
224         }
225     }
226
227     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
228         if_chain! {
229             if !in_macro(expr.span);
230             if meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS);
231             if let Some(&StackItem::Check { impl_id, .. }) = self.stack.last();
232             if cx.typeck_results().expr_ty(expr) == cx.tcx.type_of(impl_id);
233             then {} else { return; }
234         }
235         match expr.kind {
236             ExprKind::Struct(QPath::Resolved(_, path), ..) => match path.res {
237                 Res::SelfTy(..) => (),
238                 Res::Def(DefKind::Variant, _) => lint_path_to_variant(cx, path),
239                 _ => span_lint(cx, path.span),
240             },
241             // tuple struct instantiation (`Foo(arg)` or `Enum::Foo(arg)`)
242             ExprKind::Call(fun, _) => {
243                 if let ExprKind::Path(QPath::Resolved(_, path)) = fun.kind {
244                     if let Res::Def(DefKind::Ctor(ctor_of, _), ..) = path.res {
245                         match ctor_of {
246                             CtorOf::Variant => lint_path_to_variant(cx, path),
247                             CtorOf::Struct => span_lint(cx, path.span),
248                         }
249                     }
250                 }
251             },
252             // unit enum variants (`Enum::A`)
253             ExprKind::Path(QPath::Resolved(_, path)) => lint_path_to_variant(cx, path),
254             _ => (),
255         }
256     }
257
258     extract_msrv_attr!(LateContext);
259 }
260
261 #[derive(Default)]
262 struct SkipTyCollector {
263     types_to_skip: Vec<HirId>,
264 }
265
266 impl<'tcx> Visitor<'tcx> for SkipTyCollector {
267     type Map = Map<'tcx>;
268
269     fn visit_ty(&mut self, hir_ty: &hir::Ty<'_>) {
270         self.types_to_skip.push(hir_ty.hir_id);
271
272         walk_ty(self, hir_ty);
273     }
274
275     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
276         NestedVisitorMap::None
277     }
278 }
279
280 fn span_lint(cx: &LateContext<'_>, span: Span) {
281     span_lint_and_sugg(
282         cx,
283         USE_SELF,
284         span,
285         "unnecessary structure name repetition",
286         "use the applicable keyword",
287         "Self".to_owned(),
288         Applicability::MachineApplicable,
289     );
290 }
291
292 fn lint_path_to_variant(cx: &LateContext<'_>, path: &Path<'_>) {
293     if let [.., self_seg, _variant] = path.segments {
294         let span = path
295             .span
296             .with_hi(self_seg.args().span_ext().unwrap_or(self_seg.ident.span).hi());
297         span_lint(cx, span);
298     }
299 }
300
301 fn is_item_interesting(item: &Item<'_>) -> bool {
302     use rustc_hir::ItemKind::{Const, Enum, Fn, Impl, Static, Struct, Trait, Union};
303     matches!(
304         item.kind,
305         Impl { .. } | Static(..) | Const(..) | Fn(..) | Enum(..) | Struct(..) | Union(..) | Trait(..)
306     )
307 }