]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/use_self.rs
Auto merge of #9546 - kraktus:default_not_default_trait, r=xFrednet
[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::{is_from_proc_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_inf, walk_ty, Visitor},
12     Expr, ExprKind, FnRetTy, FnSig, GenericArg, HirId, Impl, ImplItemKind, Item, ItemKind, Pat, PatKind, Path, QPath,
13     TyKind,
14 };
15 use rustc_lint::{LateContext, LateLintPass};
16 use rustc_semver::RustcVersion;
17 use rustc_session::{declare_tool_lint, impl_lint_pass};
18 use rustc_span::Span;
19 use rustc_typeck::hir_ty_to_ty;
20
21 declare_clippy_lint! {
22     /// ### What it does
23     /// Checks for unnecessary repetition of structure name when a
24     /// replacement with `Self` is applicable.
25     ///
26     /// ### Why is this bad?
27     /// Unnecessary repetition. Mixed use of `Self` and struct
28     /// name
29     /// feels inconsistent.
30     ///
31     /// ### Known problems
32     /// - Unaddressed false negative in fn bodies of trait implementations
33     /// - False positive with associated types in traits (#4140)
34     ///
35     /// ### Example
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     #[clippy::version = "pre 1.29.0"]
54     pub USE_SELF,
55     nursery,
56     "unnecessary structure name repetition whereas `Self` is applicable"
57 }
58
59 #[derive(Default)]
60 pub struct UseSelf {
61     msrv: Option<RustcVersion>,
62     stack: Vec<StackItem>,
63 }
64
65 impl UseSelf {
66     #[must_use]
67     pub fn new(msrv: Option<RustcVersion>) -> Self {
68         Self {
69             msrv,
70             ..Self::default()
71         }
72     }
73 }
74
75 #[derive(Debug)]
76 enum StackItem {
77     Check {
78         impl_id: LocalDefId,
79         in_body: u32,
80         types_to_skip: FxHashSet<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<'tcx>, item: &Item<'tcx>) {
91         if matches!(item.kind, ItemKind::OpaqueTy(_)) {
92             // skip over `ItemKind::OpaqueTy` in order to lint `foo() -> impl <..>`
93             return;
94         }
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(_)))
105             });
106             if !is_from_proc_macro(cx, item); // expensive, should be last check
107             then {
108                 StackItem::Check {
109                     impl_id: item.def_id,
110                     in_body: 0,
111                     types_to_skip: std::iter::once(self_ty.hir_id).collect(),
112                 }
113             } else {
114                 StackItem::NoCheck
115             }
116         };
117         self.stack.push(stack_item);
118     }
119
120     fn check_item_post(&mut self, _: &LateContext<'_>, item: &Item<'_>) {
121         if !matches!(item.kind, ItemKind::OpaqueTy(_)) {
122             self.stack.pop();
123         }
124     }
125
126     fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
127         // We want to skip types in trait `impl`s that aren't declared as `Self` in the trait
128         // declaration. The collection of those types is all this method implementation does.
129         if_chain! {
130             if let ImplItemKind::Fn(FnSig { decl, .. }, ..) = impl_item.kind;
131             if let Some(&mut StackItem::Check {
132                 impl_id,
133                 ref mut types_to_skip,
134                 ..
135             }) = self.stack.last_mut();
136             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_id);
137             then {
138                 // `self_ty` is the semantic self type of `impl <trait> for <type>`. This cannot be
139                 // `Self`.
140                 let self_ty = impl_trait_ref.self_ty();
141
142                 // `trait_method_sig` is the signature of the function, how it is declared in the
143                 // trait, not in the impl of the trait.
144                 let trait_method = cx
145                     .tcx
146                     .associated_item(impl_item.def_id)
147                     .trait_item_def_id
148                     .expect("impl method matches a trait method");
149                 let trait_method_sig = cx.tcx.fn_sig(trait_method);
150                 let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig);
151
152                 // `impl_inputs_outputs` is an iterator over the types (`hir::Ty`) declared in the
153                 // implementation of the trait.
154                 let output_hir_ty = if let FnRetTy::Return(ty) = &decl.output {
155                     Some(&**ty)
156                 } else {
157                     None
158                 };
159                 let impl_inputs_outputs = decl.inputs.iter().chain(output_hir_ty);
160
161                 // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature.
162                 //
163                 // `trait_sem_ty` (of type `ty::Ty`) is the semantic type for the signature in the
164                 // trait declaration. This is used to check if `Self` was used in the trait
165                 // declaration.
166                 //
167                 // If `any`where in the `trait_sem_ty` the `self_ty` was used verbatim (as opposed
168                 // to `Self`), we want to skip linting that type and all subtypes of it. This
169                 // avoids suggestions to e.g. replace `Vec<u8>` with `Vec<Self>`, in an `impl Trait
170                 // for u8`, when the trait always uses `Vec<u8>`.
171                 //
172                 // See also https://github.com/rust-lang/rust-clippy/issues/2894.
173                 for (impl_hir_ty, trait_sem_ty) in impl_inputs_outputs.zip(trait_method_sig.inputs_and_output) {
174                     if trait_sem_ty.walk().any(|inner| inner == self_ty.into()) {
175                         let mut visitor = SkipTyCollector::default();
176                         visitor.visit_ty(impl_hir_ty);
177                         types_to_skip.extend(visitor.types_to_skip);
178                     }
179                 }
180             }
181         }
182     }
183
184     fn check_body(&mut self, _: &LateContext<'_>, _: &hir::Body<'_>) {
185         // `hir_ty_to_ty` cannot be called in `Body`s or it will panic (sometimes). But in bodies
186         // we can use `cx.typeck_results.node_type(..)` to get the `ty::Ty` from a `hir::Ty`.
187         // However the `node_type()` method can *only* be called in bodies.
188         if let Some(&mut StackItem::Check { ref mut in_body, .. }) = self.stack.last_mut() {
189             *in_body = in_body.saturating_add(1);
190         }
191     }
192
193     fn check_body_post(&mut self, _: &LateContext<'_>, _: &hir::Body<'_>) {
194         if let Some(&mut StackItem::Check { ref mut in_body, .. }) = self.stack.last_mut() {
195             *in_body = in_body.saturating_sub(1);
196         }
197     }
198
199     fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
200         if_chain! {
201             if !hir_ty.span.from_expansion();
202             if meets_msrv(self.msrv, msrvs::TYPE_ALIAS_ENUM_VARIANTS);
203             if let Some(&StackItem::Check {
204                 impl_id,
205                 in_body,
206                 ref types_to_skip,
207             }) = self.stack.last();
208             if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind;
209             if !matches!(path.res, Res::SelfTy { .. } | Res::Def(DefKind::TyParam, _));
210             if !types_to_skip.contains(&hir_ty.hir_id);
211             let ty = if in_body > 0 {
212                 cx.typeck_results().node_type(hir_ty.hir_id)
213             } else {
214                 hir_ty_to_ty(cx.tcx, hir_ty)
215             };
216             if same_type_and_consts(ty, cx.tcx.type_of(impl_id));
217             then {
218                 span_lint(cx, hir_ty.span);
219             }
220         }
221     }
222
223     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
224         if_chain! {
225             if !expr.span.from_expansion();
226             if meets_msrv(self.msrv, msrvs::TYPE_ALIAS_ENUM_VARIANTS);
227             if let Some(&StackItem::Check { impl_id, .. }) = self.stack.last();
228             if cx.typeck_results().expr_ty(expr) == cx.tcx.type_of(impl_id);
229             then {} else { return; }
230         }
231         match expr.kind {
232             ExprKind::Struct(QPath::Resolved(_, path), ..) => match path.res {
233                 Res::SelfTy { .. } => (),
234                 Res::Def(DefKind::Variant, _) => lint_path_to_variant(cx, path),
235                 _ => span_lint(cx, path.span),
236             },
237             // tuple struct instantiation (`Foo(arg)` or `Enum::Foo(arg)`)
238             ExprKind::Call(fun, _) => {
239                 if let ExprKind::Path(QPath::Resolved(_, path)) = fun.kind {
240                     if let Res::Def(DefKind::Ctor(ctor_of, _), ..) = path.res {
241                         match ctor_of {
242                             CtorOf::Variant => lint_path_to_variant(cx, path),
243                             CtorOf::Struct => span_lint(cx, path.span),
244                         }
245                     }
246                 }
247             },
248             // unit enum variants (`Enum::A`)
249             ExprKind::Path(QPath::Resolved(_, path)) => lint_path_to_variant(cx, path),
250             _ => (),
251         }
252     }
253
254     fn check_pat(&mut self, cx: &LateContext<'_>, pat: &Pat<'_>) {
255         if_chain! {
256             if !pat.span.from_expansion();
257             if meets_msrv(self.msrv, msrvs::TYPE_ALIAS_ENUM_VARIANTS);
258             if let Some(&StackItem::Check { impl_id, .. }) = self.stack.last();
259             // get the path from the pattern
260             if let PatKind::Path(QPath::Resolved(_, path))
261                  | PatKind::TupleStruct(QPath::Resolved(_, path), _, _)
262                  | PatKind::Struct(QPath::Resolved(_, path), _, _) = pat.kind;
263             if cx.typeck_results().pat_ty(pat) == cx.tcx.type_of(impl_id);
264             then {
265                 match path.res {
266                     Res::Def(DefKind::Ctor(ctor_of, _), ..) => match ctor_of {
267                             CtorOf::Variant => lint_path_to_variant(cx, path),
268                             CtorOf::Struct => span_lint(cx, path.span),
269                     },
270                     Res::Def(DefKind::Variant, ..) => lint_path_to_variant(cx, path),
271                     Res::Def(DefKind::Struct, ..) => span_lint(cx, path.span),
272                     _ => ()
273                 }
274             }
275         }
276     }
277
278     extract_msrv_attr!(LateContext);
279 }
280
281 #[derive(Default)]
282 struct SkipTyCollector {
283     types_to_skip: Vec<HirId>,
284 }
285
286 impl<'tcx> Visitor<'tcx> for SkipTyCollector {
287     fn visit_infer(&mut self, inf: &hir::InferArg) {
288         self.types_to_skip.push(inf.hir_id);
289
290         walk_inf(self, inf);
291     }
292     fn visit_ty(&mut self, hir_ty: &hir::Ty<'_>) {
293         self.types_to_skip.push(hir_ty.hir_id);
294
295         walk_ty(self, hir_ty);
296     }
297 }
298
299 fn span_lint(cx: &LateContext<'_>, span: Span) {
300     span_lint_and_sugg(
301         cx,
302         USE_SELF,
303         span,
304         "unnecessary structure name repetition",
305         "use the applicable keyword",
306         "Self".to_owned(),
307         Applicability::MachineApplicable,
308     );
309 }
310
311 fn lint_path_to_variant(cx: &LateContext<'_>, path: &Path<'_>) {
312     if let [.., self_seg, _variant] = path.segments {
313         let span = path
314             .span
315             .with_hi(self_seg.args().span_ext().unwrap_or(self_seg.ident.span).hi());
316         span_lint(cx, span);
317     }
318 }