]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/use_self.rs
Simplify in impl check
[rust.git] / 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, Node, Path, QPath, TyKind,
13 };
14 use rustc_lint::{LateContext, LateLintPass, LintContext};
15 use rustc_middle::hir::map::Map;
16 use rustc_middle::ty::{AssocKind, Ty};
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         hir_id: HirId,
78         impl_trait_ref_def_id: Option<LocalDefId>,
79         types_to_skip: FxHashSet<HirId>,
80         types_to_lint: Vec<HirId>,
81     },
82     NoCheck,
83 }
84
85 impl_lint_pass!(UseSelf => [USE_SELF]);
86
87 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
88
89 impl<'tcx> LateLintPass<'tcx> for UseSelf {
90     fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
91         if !is_item_interesting(item) {
92             // This does two things:
93             //  1) Reduce needless churn on `self.stack`
94             //  2) Don't push `StackItem::NoCheck` when entering `ItemKind::OpaqueTy`,
95             //     in order to lint `foo() -> impl <..>`
96             return;
97         }
98         // We push the self types of `impl`s on a stack here. Only the top type on the stack is
99         // relevant for linting, since this is the self type of the `impl` we're currently in. To
100         // avoid linting on nested items, we push `StackItem::NoCheck` on the stack to signal, that
101         // we're in an `impl` or nested item, that we don't want to lint
102         let stack_item = if_chain! {
103             if let ItemKind::Impl(Impl { self_ty, ref of_trait, .. }) = item.kind;
104             if let TyKind::Path(QPath::Resolved(_, item_path)) = self_ty.kind;
105             let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
106             if parameters.as_ref().map_or(true, |params| {
107                 !params.parenthesized && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
108             });
109             then {
110                 let impl_trait_ref_def_id = of_trait.as_ref().map(|_| cx.tcx.hir().local_def_id(item.hir_id()));
111                 StackItem::Check {
112                     hir_id: self_ty.hir_id,
113                     impl_trait_ref_def_id,
114                     types_to_lint: Vec::new(),
115                     types_to_skip: std::iter::once(self_ty.hir_id).collect(),
116                 }
117             } else {
118                 StackItem::NoCheck
119             }
120         };
121         self.stack.push(stack_item);
122     }
123
124     fn check_item_post(&mut self, _: &LateContext<'_>, item: &Item<'_>) {
125         if is_item_interesting(item) {
126             self.stack.pop();
127         }
128     }
129
130     fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
131         // We want to skip types in trait `impl`s that aren't declared as `Self` in the trait
132         // declaration. The collection of those types is all this method implementation does.
133         if_chain! {
134             if let ImplItemKind::Fn(FnSig { decl, .. }, ..) = impl_item.kind;
135             if let Some(&mut StackItem::Check {
136                 impl_trait_ref_def_id: Some(def_id),
137                 ref mut types_to_skip,
138                 ..
139             }) = self.stack.last_mut();
140             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(def_id);
141             then {
142                 // `self_ty` is the semantic self type of `impl <trait> for <type>`. This cannot be
143                 // `Self`.
144                 let self_ty = impl_trait_ref.self_ty();
145
146                 // `trait_method_sig` is the signature of the function, how it is declared in the
147                 // trait, not in the impl of the trait.
148                 let trait_method = cx
149                     .tcx
150                     .associated_items(impl_trait_ref.def_id)
151                     .find_by_name_and_kind(cx.tcx, impl_item.ident, AssocKind::Fn, impl_trait_ref.def_id)
152                     .expect("impl method matches a trait method");
153                 let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
154                 let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig);
155
156                 // `impl_inputs_outputs` is an iterator over the types (`hir::Ty`) declared in the
157                 // implementation of the trait.
158                 let output_hir_ty = if let FnRetTy::Return(ty) = &decl.output {
159                     Some(&**ty)
160                 } else {
161                     None
162                 };
163                 let impl_inputs_outputs = decl.inputs.iter().chain(output_hir_ty);
164
165                 // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature.
166                 //
167                 // `trait_sem_ty` (of type `ty::Ty`) is the semantic type for the signature in the
168                 // trait declaration. This is used to check if `Self` was used in the trait
169                 // declaration.
170                 //
171                 // If `any`where in the `trait_sem_ty` the `self_ty` was used verbatim (as opposed
172                 // to `Self`), we want to skip linting that type and all subtypes of it. This
173                 // avoids suggestions to e.g. replace `Vec<u8>` with `Vec<Self>`, in an `impl Trait
174                 // for u8`, when the trait always uses `Vec<u8>`.
175                 //
176                 // See also https://github.com/rust-lang/rust-clippy/issues/2894.
177                 for (impl_hir_ty, trait_sem_ty) in impl_inputs_outputs.zip(trait_method_sig.inputs_and_output) {
178                     if trait_sem_ty.walk().any(|inner| inner == self_ty.into()) {
179                         let mut visitor = SkipTyCollector::default();
180                         visitor.visit_ty(impl_hir_ty);
181                         types_to_skip.extend(visitor.types_to_skip);
182                     }
183                 }
184             }
185         }
186     }
187
188     fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) {
189         // `hir_ty_to_ty` cannot be called in `Body`s or it will panic (sometimes). But in bodies
190         // we can use `cx.typeck_results.node_type(..)` to get the `ty::Ty` from a `hir::Ty`.
191         // However the `node_type()` method can *only* be called in bodies.
192         //
193         // This method implementation determines which types should get linted in a `Body` and
194         // which shouldn't, with a visitor. We could directly lint in the visitor, but then we
195         // could only allow this lint on item scope. And we would have to check if those types are
196         // already dealt with in `check_ty` anyway.
197         if let Some(StackItem::Check {
198             hir_id,
199             types_to_lint,
200             types_to_skip,
201             ..
202         }) = self.stack.last_mut()
203         {
204             let self_ty = ty_from_hir_id(cx, *hir_id);
205
206             let mut visitor = LintTyCollector {
207                 cx,
208                 self_ty,
209                 types_to_lint: vec![],
210                 types_to_skip: vec![],
211             };
212             visitor.visit_expr(&body.value);
213             types_to_lint.extend(visitor.types_to_lint);
214             types_to_skip.extend(visitor.types_to_skip);
215         }
216     }
217
218     fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
219         if_chain! {
220             if !in_macro(hir_ty.span);
221             if meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS);
222             if let Some(StackItem::Check {
223                 hir_id,
224                 types_to_lint,
225                 types_to_skip,
226                 ..
227             }) = self.stack.last();
228             if !types_to_skip.contains(&hir_ty.hir_id);
229             if types_to_lint.contains(&hir_ty.hir_id)
230                 || {
231                     let self_ty = ty_from_hir_id(cx, *hir_id);
232                     should_lint_ty(hir_ty, hir_ty_to_ty(cx.tcx, hir_ty), self_ty)
233                 };
234             let hir = cx.tcx.hir();
235             let id = hir.get_parent_node(hir_ty.hir_id);
236             if !hir.opt_span(id).map_or(false, in_macro);
237             then {
238                 span_lint(cx, hir_ty.span);
239             }
240         }
241     }
242
243     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
244         if_chain! {
245             if !in_macro(expr.span);
246             if meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS);
247             if let Some(StackItem::Check { hir_id, .. }) = self.stack.last();
248             if cx.typeck_results().expr_ty(expr) == ty_from_hir_id(cx, *hir_id);
249             then {} else { return; }
250         }
251         match expr.kind {
252             ExprKind::Struct(QPath::Resolved(_, path), ..) => match path.res {
253                 Res::SelfTy(..) => (),
254                 Res::Def(DefKind::Variant, _) => lint_path_to_variant(cx, path),
255                 _ => span_lint(cx, path.span),
256             },
257             // tuple struct instantiation (`Foo(arg)` or `Enum::Foo(arg)`)
258             ExprKind::Call(fun, _) => {
259                 if let ExprKind::Path(QPath::Resolved(_, path)) = fun.kind {
260                     if let Res::Def(DefKind::Ctor(ctor_of, _), ..) = path.res {
261                         match ctor_of {
262                             CtorOf::Variant => lint_path_to_variant(cx, path),
263                             CtorOf::Struct => span_lint(cx, path.span),
264                         }
265                     }
266                 }
267             },
268             // unit enum variants (`Enum::A`)
269             ExprKind::Path(QPath::Resolved(_, path)) => lint_path_to_variant(cx, path),
270             _ => (),
271         }
272     }
273
274     extract_msrv_attr!(LateContext);
275 }
276
277 #[derive(Default)]
278 struct SkipTyCollector {
279     types_to_skip: Vec<HirId>,
280 }
281
282 impl<'tcx> Visitor<'tcx> for SkipTyCollector {
283     type Map = Map<'tcx>;
284
285     fn visit_ty(&mut self, hir_ty: &hir::Ty<'_>) {
286         self.types_to_skip.push(hir_ty.hir_id);
287
288         walk_ty(self, hir_ty);
289     }
290
291     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
292         NestedVisitorMap::None
293     }
294 }
295
296 struct LintTyCollector<'a, 'tcx> {
297     cx: &'a LateContext<'tcx>,
298     self_ty: Ty<'tcx>,
299     types_to_lint: Vec<HirId>,
300     types_to_skip: Vec<HirId>,
301 }
302
303 impl<'a, 'tcx> Visitor<'tcx> for LintTyCollector<'a, 'tcx> {
304     type Map = Map<'tcx>;
305
306     fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'_>) {
307         if_chain! {
308             if let Some(ty) = self.cx.typeck_results().node_type_opt(hir_ty.hir_id);
309             if should_lint_ty(hir_ty, ty, self.self_ty);
310             then {
311                 self.types_to_lint.push(hir_ty.hir_id);
312             } else {
313                 self.types_to_skip.push(hir_ty.hir_id);
314             }
315         }
316
317         walk_ty(self, hir_ty);
318     }
319
320     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
321         NestedVisitorMap::None
322     }
323 }
324
325 fn span_lint(cx: &LateContext<'_>, span: Span) {
326     span_lint_and_sugg(
327         cx,
328         USE_SELF,
329         span,
330         "unnecessary structure name repetition",
331         "use the applicable keyword",
332         "Self".to_owned(),
333         Applicability::MachineApplicable,
334     );
335 }
336
337 fn lint_path_to_variant(cx: &LateContext<'_>, path: &Path<'_>) {
338     if let [.., self_seg, _variant] = path.segments {
339         let span = path
340             .span
341             .with_hi(self_seg.args().span_ext().unwrap_or(self_seg.ident.span).hi());
342         span_lint(cx, span);
343     }
344 }
345
346 fn is_item_interesting(item: &Item<'_>) -> bool {
347     use rustc_hir::ItemKind::{Const, Enum, Fn, Impl, Static, Struct, Trait, Union};
348     matches!(
349         item.kind,
350         Impl { .. } | Static(..) | Const(..) | Fn(..) | Enum(..) | Struct(..) | Union(..) | Trait(..)
351     )
352 }
353
354 fn ty_from_hir_id<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Ty<'tcx> {
355     if let Some(Node::Ty(hir_ty)) = cx.tcx.hir().find(hir_id) {
356         hir_ty_to_ty(cx.tcx, hir_ty)
357     } else {
358         unreachable!("This function should only be called with `HirId`s that are for sure `Node::Ty`")
359     }
360 }
361
362 fn should_lint_ty(hir_ty: &hir::Ty<'_>, ty: Ty<'_>, self_ty: Ty<'_>) -> bool {
363     if_chain! {
364         if same_type_and_consts(ty, self_ty);
365         if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind;
366         then {
367             !matches!(path.res, Res::SelfTy(..) | Res::Def(DefKind::TyParam, _))
368         } else {
369             false
370         }
371     }
372 }