]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/use_self.rs
Rollup merge of #86783 - mark-i-m:mutex-drop-unsized, r=Xanewok
[rust.git] / src / tools / clippy / clippy_lints / src / use_self.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::ty::same_type_and_consts;
4 use clippy_utils::{in_macro, meets_msrv, msrvs};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::{
8     self as hir,
9     def::{self, DefKind},
10     def_id::LocalDefId,
11     intravisit::{walk_ty, NestedVisitorMap, Visitor},
12     Expr, ExprKind, FnRetTy, FnSig, GenericArg, HirId, Impl, ImplItemKind, Item, ItemKind, Node, Path, PathSegment,
13     QPath, TyKind,
14 };
15 use rustc_lint::{LateContext, LateLintPass, LintContext};
16 use rustc_middle::hir::map::Map;
17 use rustc_middle::ty::{AssocKind, Ty};
18 use rustc_semver::RustcVersion;
19 use rustc_session::{declare_tool_lint, impl_lint_pass};
20 use rustc_span::{BytePos, Span};
21 use rustc_typeck::hir_ty_to_ty;
22
23 declare_clippy_lint! {
24     /// **What it does:** Checks for unnecessary repetition of structure name when a
25     /// replacement with `Self` is applicable.
26     ///
27     /// **Why is this bad?** 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 assotiated types in traits (#4140)
34     ///
35     /// **Example:**
36     ///
37     /// ```rust
38     /// struct Foo {}
39     /// impl Foo {
40     ///     fn new() -> Foo {
41     ///         Foo {}
42     ///     }
43     /// }
44     /// ```
45     /// could be
46     /// ```rust
47     /// struct Foo {}
48     /// impl Foo {
49     ///     fn new() -> Self {
50     ///         Self {}
51     ///     }
52     /// }
53     /// ```
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         hir_id: HirId,
79         impl_trait_ref_def_id: Option<LocalDefId>,
80         types_to_skip: Vec<HirId>,
81         types_to_lint: Vec<HirId>,
82     },
83     NoCheck,
84 }
85
86 impl_lint_pass!(UseSelf => [USE_SELF]);
87
88 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
89
90 impl<'tcx> LateLintPass<'tcx> for UseSelf {
91     fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
92         // We push the self types of `impl`s on a stack here. Only the top type on the stack is
93         // relevant for linting, since this is the self type of the `impl` we're currently in. To
94         // avoid linting on nested items, we push `StackItem::NoCheck` on the stack to signal, that
95         // we're in an `impl` or nested item, that we don't want to lint
96         //
97         // NB: If you push something on the stack in this method, remember to also pop it in the
98         // `check_item_post` method.
99         match &item.kind {
100             ItemKind::Impl(Impl {
101                 self_ty: hir_self_ty,
102                 of_trait,
103                 ..
104             }) => {
105                 let should_check = if let TyKind::Path(QPath::Resolved(_, item_path)) = hir_self_ty.kind {
106                     let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
107                     parameters.as_ref().map_or(true, |params| {
108                         !params.parenthesized && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
109                     })
110                 } else {
111                     false
112                 };
113                 let impl_trait_ref_def_id = of_trait.as_ref().map(|_| cx.tcx.hir().local_def_id(item.hir_id()));
114                 if should_check {
115                     self.stack.push(StackItem::Check {
116                         hir_id: hir_self_ty.hir_id,
117                         impl_trait_ref_def_id,
118                         types_to_lint: Vec::new(),
119                         types_to_skip: Vec::new(),
120                     });
121                 } else {
122                     self.stack.push(StackItem::NoCheck);
123                 }
124             },
125             ItemKind::Static(..)
126             | ItemKind::Const(..)
127             | ItemKind::Fn(..)
128             | ItemKind::Enum(..)
129             | ItemKind::Struct(..)
130             | ItemKind::Union(..)
131             | ItemKind::Trait(..) => {
132                 self.stack.push(StackItem::NoCheck);
133             },
134             _ => (),
135         }
136     }
137
138     fn check_item_post(&mut self, _: &LateContext<'_>, item: &Item<'_>) {
139         use ItemKind::{Const, Enum, Fn, Impl, Static, Struct, Trait, Union};
140         match item.kind {
141             Impl { .. } | Static(..) | Const(..) | Fn(..) | Enum(..) | Struct(..) | Union(..) | Trait(..) => {
142                 self.stack.pop();
143             },
144             _ => (),
145         }
146     }
147
148     fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
149         // We want to skip types in trait `impl`s that aren't declared as `Self` in the trait
150         // declaration. The collection of those types is all this method implementation does.
151         if_chain! {
152             if let ImplItemKind::Fn(FnSig { decl, .. }, ..) = impl_item.kind;
153             if let Some(&mut StackItem::Check {
154                 impl_trait_ref_def_id: Some(def_id),
155                 ref mut types_to_skip,
156                 ..
157             }) = self.stack.last_mut();
158             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(def_id);
159             then {
160                 // `self_ty` is the semantic self type of `impl <trait> for <type>`. This cannot be
161                 // `Self`.
162                 let self_ty = impl_trait_ref.self_ty();
163
164                 // `trait_method_sig` is the signature of the function, how it is declared in the
165                 // trait, not in the impl of the trait.
166                 let trait_method = cx
167                     .tcx
168                     .associated_items(impl_trait_ref.def_id)
169                     .find_by_name_and_kind(cx.tcx, impl_item.ident, AssocKind::Fn, impl_trait_ref.def_id)
170                     .expect("impl method matches a trait method");
171                 let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
172                 let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig);
173
174                 // `impl_inputs_outputs` is an iterator over the types (`hir::Ty`) declared in the
175                 // implementation of the trait.
176                 let output_hir_ty = if let FnRetTy::Return(ty) = &decl.output {
177                     Some(&**ty)
178                 } else {
179                     None
180                 };
181                 let impl_inputs_outputs = decl.inputs.iter().chain(output_hir_ty);
182
183                 // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature.
184                 //
185                 // `trait_sem_ty` (of type `ty::Ty`) is the semantic type for the signature in the
186                 // trait declaration. This is used to check if `Self` was used in the trait
187                 // declaration.
188                 //
189                 // If `any`where in the `trait_sem_ty` the `self_ty` was used verbatim (as opposed
190                 // to `Self`), we want to skip linting that type and all subtypes of it. This
191                 // avoids suggestions to e.g. replace `Vec<u8>` with `Vec<Self>`, in an `impl Trait
192                 // for u8`, when the trait always uses `Vec<u8>`.
193                 //
194                 // See also https://github.com/rust-lang/rust-clippy/issues/2894.
195                 for (impl_hir_ty, trait_sem_ty) in impl_inputs_outputs.zip(trait_method_sig.inputs_and_output) {
196                     if trait_sem_ty.walk().any(|inner| inner == self_ty.into()) {
197                         let mut visitor = SkipTyCollector::default();
198                         visitor.visit_ty(impl_hir_ty);
199                         types_to_skip.extend(visitor.types_to_skip);
200                     }
201                 }
202             }
203         }
204     }
205
206     fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) {
207         // `hir_ty_to_ty` cannot be called in `Body`s or it will panic (sometimes). But in bodies
208         // we can use `cx.typeck_results.node_type(..)` to get the `ty::Ty` from a `hir::Ty`.
209         // However the `node_type()` method can *only* be called in bodies.
210         //
211         // This method implementation determines which types should get linted in a `Body` and
212         // which shouldn't, with a visitor. We could directly lint in the visitor, but then we
213         // could only allow this lint on item scope. And we would have to check if those types are
214         // already dealt with in `check_ty` anyway.
215         if let Some(StackItem::Check {
216             hir_id,
217             types_to_lint,
218             types_to_skip,
219             ..
220         }) = self.stack.last_mut()
221         {
222             let self_ty = ty_from_hir_id(cx, *hir_id);
223
224             let mut visitor = LintTyCollector {
225                 cx,
226                 self_ty,
227                 types_to_lint: vec![],
228                 types_to_skip: vec![],
229             };
230             visitor.visit_expr(&body.value);
231             types_to_lint.extend(visitor.types_to_lint);
232             types_to_skip.extend(visitor.types_to_skip);
233         }
234     }
235
236     fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
237         if in_macro(hir_ty.span)
238             || in_impl(cx, hir_ty)
239             || !meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS)
240         {
241             return;
242         }
243
244         let lint_dependend_on_expr_kind = if let Some(StackItem::Check {
245             hir_id,
246             types_to_lint,
247             types_to_skip,
248             ..
249         }) = self.stack.last()
250         {
251             if types_to_skip.contains(&hir_ty.hir_id) {
252                 false
253             } else if types_to_lint.contains(&hir_ty.hir_id) {
254                 true
255             } else {
256                 let self_ty = ty_from_hir_id(cx, *hir_id);
257                 should_lint_ty(hir_ty, hir_ty_to_ty(cx.tcx, hir_ty), self_ty)
258             }
259         } else {
260             false
261         };
262
263         if lint_dependend_on_expr_kind {
264             // FIXME: this span manipulation should not be necessary
265             // @flip1995 found an ast lowering issue in
266             // https://github.com/rust-lang/rust/blob/master/src/librustc_ast_lowering/path.rs#l142-l162
267             let hir = cx.tcx.hir();
268             let id = hir.get_parent_node(hir_ty.hir_id);
269
270             if !hir.opt_span(id).map_or(false, in_macro) {
271                 match hir.find(id) {
272                     Some(Node::Expr(Expr {
273                         kind: ExprKind::Path(QPath::TypeRelative(_, segment)),
274                         ..
275                     })) => span_lint_until_last_segment(cx, hir_ty.span, segment),
276                     _ => span_lint(cx, hir_ty.span),
277                 }
278             }
279         }
280     }
281
282     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
283         fn expr_ty_matches(cx: &LateContext<'_>, expr: &Expr<'_>, self_ty: Ty<'_>) -> bool {
284             let def_id = expr.hir_id.owner;
285             if cx.tcx.has_typeck_results(def_id) {
286                 cx.tcx.typeck(def_id).expr_ty_opt(expr) == Some(self_ty)
287             } else {
288                 false
289             }
290         }
291
292         if in_macro(expr.span) || !meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS) {
293             return;
294         }
295
296         if let Some(StackItem::Check { hir_id, .. }) = self.stack.last() {
297             let self_ty = ty_from_hir_id(cx, *hir_id);
298
299             match &expr.kind {
300                 ExprKind::Struct(QPath::Resolved(_, path), ..) => {
301                     if expr_ty_matches(cx, expr, self_ty) {
302                         match path.res {
303                             def::Res::SelfTy(..) => (),
304                             def::Res::Def(DefKind::Variant, _) => span_lint_on_path_until_last_segment(cx, path),
305                             _ => {
306                                 span_lint(cx, path.span);
307                             },
308                         }
309                     }
310                 },
311                 // tuple struct instantiation (`Foo(arg)` or `Enum::Foo(arg)`)
312                 ExprKind::Call(fun, _) => {
313                     if let Expr {
314                         kind: ExprKind::Path(ref qpath),
315                         ..
316                     } = fun
317                     {
318                         if expr_ty_matches(cx, expr, self_ty) {
319                             let res = cx.qpath_res(qpath, fun.hir_id);
320
321                             if let def::Res::Def(DefKind::Ctor(ctor_of, _), ..) = res {
322                                 match ctor_of {
323                                     def::CtorOf::Variant => {
324                                         span_lint_on_qpath_resolved(cx, qpath, true);
325                                     },
326                                     def::CtorOf::Struct => {
327                                         span_lint_on_qpath_resolved(cx, qpath, false);
328                                     },
329                                 }
330                             }
331                         }
332                     }
333                 },
334                 // unit enum variants (`Enum::A`)
335                 ExprKind::Path(qpath) => {
336                     if expr_ty_matches(cx, expr, self_ty) {
337                         span_lint_on_qpath_resolved(cx, qpath, true);
338                     }
339                 },
340                 _ => (),
341             }
342         }
343     }
344
345     extract_msrv_attr!(LateContext);
346 }
347
348 #[derive(Default)]
349 struct SkipTyCollector {
350     types_to_skip: Vec<HirId>,
351 }
352
353 impl<'tcx> Visitor<'tcx> for SkipTyCollector {
354     type Map = Map<'tcx>;
355
356     fn visit_ty(&mut self, hir_ty: &hir::Ty<'_>) {
357         self.types_to_skip.push(hir_ty.hir_id);
358
359         walk_ty(self, hir_ty);
360     }
361
362     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
363         NestedVisitorMap::None
364     }
365 }
366
367 struct LintTyCollector<'a, 'tcx> {
368     cx: &'a LateContext<'tcx>,
369     self_ty: Ty<'tcx>,
370     types_to_lint: Vec<HirId>,
371     types_to_skip: Vec<HirId>,
372 }
373
374 impl<'a, 'tcx> Visitor<'tcx> for LintTyCollector<'a, 'tcx> {
375     type Map = Map<'tcx>;
376
377     fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'_>) {
378         if_chain! {
379             if let Some(ty) = self.cx.typeck_results().node_type_opt(hir_ty.hir_id);
380             if should_lint_ty(hir_ty, ty, self.self_ty);
381             then {
382                 self.types_to_lint.push(hir_ty.hir_id);
383             } else {
384                 self.types_to_skip.push(hir_ty.hir_id);
385             }
386         }
387
388         walk_ty(self, hir_ty);
389     }
390
391     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
392         NestedVisitorMap::None
393     }
394 }
395
396 fn span_lint(cx: &LateContext<'_>, span: Span) {
397     span_lint_and_sugg(
398         cx,
399         USE_SELF,
400         span,
401         "unnecessary structure name repetition",
402         "use the applicable keyword",
403         "Self".to_owned(),
404         Applicability::MachineApplicable,
405     );
406 }
407
408 #[allow(clippy::cast_possible_truncation)]
409 fn span_lint_until_last_segment(cx: &LateContext<'_>, span: Span, segment: &PathSegment<'_>) {
410     let sp = span.with_hi(segment.ident.span.lo());
411     // remove the trailing ::
412     let span_without_last_segment = match snippet_opt(cx, sp) {
413         Some(snippet) => match snippet.rfind("::") {
414             Some(bidx) => sp.with_hi(sp.lo() + BytePos(bidx as u32)),
415             None => sp,
416         },
417         None => sp,
418     };
419     span_lint(cx, span_without_last_segment);
420 }
421
422 fn span_lint_on_path_until_last_segment(cx: &LateContext<'_>, path: &Path<'_>) {
423     if path.segments.len() > 1 {
424         span_lint_until_last_segment(cx, path.span, path.segments.last().unwrap());
425     }
426 }
427
428 fn span_lint_on_qpath_resolved(cx: &LateContext<'_>, qpath: &QPath<'_>, until_last_segment: bool) {
429     if let QPath::Resolved(_, path) = qpath {
430         if until_last_segment {
431             span_lint_on_path_until_last_segment(cx, path);
432         } else {
433             span_lint(cx, path.span);
434         }
435     }
436 }
437
438 fn ty_from_hir_id<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Ty<'tcx> {
439     if let Some(Node::Ty(hir_ty)) = cx.tcx.hir().find(hir_id) {
440         hir_ty_to_ty(cx.tcx, hir_ty)
441     } else {
442         unreachable!("This function should only be called with `HirId`s that are for sure `Node::Ty`")
443     }
444 }
445
446 fn in_impl(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> bool {
447     let map = cx.tcx.hir();
448     let parent = map.get_parent_node(hir_ty.hir_id);
449     if_chain! {
450         if let Some(Node::Item(item)) = map.find(parent);
451         if let ItemKind::Impl { .. } = item.kind;
452         then {
453             true
454         } else {
455             false
456         }
457     }
458 }
459
460 fn should_lint_ty(hir_ty: &hir::Ty<'_>, ty: Ty<'_>, self_ty: Ty<'_>) -> bool {
461     if_chain! {
462         if same_type_and_consts(ty, self_ty);
463         if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind;
464         then {
465             !matches!(path.res, def::Res::SelfTy(..))
466         } else {
467             false
468         }
469     }
470 }