]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/use_self.rs
776c6bc57ca6f857c4d86b699d99a4d5f2351f41
[rust.git] / src / tools / clippy / clippy_lints / src / use_self.rs
1 use if_chain::if_chain;
2 use rustc_errors::Applicability;
3 use rustc_hir as hir;
4 use rustc_hir::def::{DefKind, Res};
5 use rustc_hir::intravisit::{walk_item, walk_path, walk_ty, NestedVisitorMap, Visitor};
6 use rustc_hir::{
7     def, FnDecl, FnRetTy, FnSig, GenericArg, HirId, ImplItem, ImplItemKind, Item, ItemKind, Path, PathSegment, QPath,
8     TyKind,
9 };
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_middle::hir::map::Map;
12 use rustc_middle::lint::in_external_macro;
13 use rustc_middle::ty;
14 use rustc_middle::ty::{DefIdTree, Ty};
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 use rustc_span::symbol::kw;
17 use rustc_typeck::hir_ty_to_ty;
18
19 use crate::utils::{differing_macro_contexts, span_lint_and_sugg};
20
21 declare_clippy_lint! {
22     /// **What it does:** Checks for unnecessary repetition of structure name when a
23     /// replacement with `Self` is applicable.
24     ///
25     /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
26     /// name
27     /// feels inconsistent.
28     ///
29     /// **Known problems:**
30     /// - False positive when using associated types (#2843)
31     /// - False positives in some situations when using generics (#3410)
32     ///
33     /// **Example:**
34     /// ```rust
35     /// struct Foo {}
36     /// impl Foo {
37     ///     fn new() -> Foo {
38     ///         Foo {}
39     ///     }
40     /// }
41     /// ```
42     /// could be
43     /// ```rust
44     /// struct Foo {}
45     /// impl Foo {
46     ///     fn new() -> Self {
47     ///         Self {}
48     ///     }
49     /// }
50     /// ```
51     pub USE_SELF,
52     nursery,
53     "Unnecessary structure name repetition whereas `Self` is applicable"
54 }
55
56 declare_lint_pass!(UseSelf => [USE_SELF]);
57
58 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
59
60 fn span_use_self_lint(cx: &LateContext<'_>, path: &Path<'_>, last_segment: Option<&PathSegment<'_>>) {
61     let last_segment = last_segment.unwrap_or_else(|| path.segments.last().expect(SEGMENTS_MSG));
62
63     // Path segments only include actual path, no methods or fields.
64     let last_path_span = last_segment.ident.span;
65
66     if differing_macro_contexts(path.span, last_path_span) {
67         return;
68     }
69
70     // Only take path up to the end of last_path_span.
71     let span = path.span.with_hi(last_path_span.hi());
72
73     span_lint_and_sugg(
74         cx,
75         USE_SELF,
76         span,
77         "unnecessary structure name repetition",
78         "use the applicable keyword",
79         "Self".to_owned(),
80         Applicability::MachineApplicable,
81     );
82 }
83
84 // FIXME: always use this (more correct) visitor, not just in method signatures.
85 struct SemanticUseSelfVisitor<'a, 'tcx> {
86     cx: &'a LateContext<'tcx>,
87     self_ty: Ty<'tcx>,
88 }
89
90 impl<'a, 'tcx> Visitor<'tcx> for SemanticUseSelfVisitor<'a, 'tcx> {
91     type Map = Map<'tcx>;
92
93     fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'_>) {
94         if let TyKind::Path(QPath::Resolved(_, path)) = &hir_ty.kind {
95             match path.res {
96                 def::Res::SelfTy(..) => {},
97                 _ => {
98                     if hir_ty_to_ty(self.cx.tcx, hir_ty) == self.self_ty {
99                         span_use_self_lint(self.cx, path, None);
100                     }
101                 },
102             }
103         }
104
105         walk_ty(self, hir_ty)
106     }
107
108     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
109         NestedVisitorMap::None
110     }
111 }
112
113 fn check_trait_method_impl_decl<'tcx>(
114     cx: &LateContext<'tcx>,
115     impl_item: &ImplItem<'_>,
116     impl_decl: &'tcx FnDecl<'_>,
117     impl_trait_ref: ty::TraitRef<'tcx>,
118 ) {
119     let trait_method = cx
120         .tcx
121         .associated_items(impl_trait_ref.def_id)
122         .find_by_name_and_kind(cx.tcx, impl_item.ident, ty::AssocKind::Fn, impl_trait_ref.def_id)
123         .expect("impl method matches a trait method");
124
125     let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
126     let trait_method_sig = cx.tcx.erase_late_bound_regions(&trait_method_sig);
127
128     let output_hir_ty = if let FnRetTy::Return(ty) = &impl_decl.output {
129         Some(&**ty)
130     } else {
131         None
132     };
133
134     // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature.
135     // `trait_ty` (of type `ty::Ty`) is the semantic type for the signature in the trait.
136     // We use `impl_hir_ty` to see if the type was written as `Self`,
137     // `hir_ty_to_ty(...)` to check semantic types of paths, and
138     // `trait_ty` to determine which parts of the signature in the trait, mention
139     // the type being implemented verbatim (as opposed to `Self`).
140     for (impl_hir_ty, trait_ty) in impl_decl
141         .inputs
142         .iter()
143         .chain(output_hir_ty)
144         .zip(trait_method_sig.inputs_and_output)
145     {
146         // Check if the input/output type in the trait method specifies the implemented
147         // type verbatim, and only suggest `Self` if that isn't the case.
148         // This avoids suggestions to e.g. replace `Vec<u8>` with `Vec<Self>`,
149         // in an `impl Trait for u8`, when the trait always uses `Vec<u8>`.
150         // See also https://github.com/rust-lang/rust-clippy/issues/2894.
151         let self_ty = impl_trait_ref.self_ty();
152         if !trait_ty.walk().any(|inner| inner == self_ty.into()) {
153             let mut visitor = SemanticUseSelfVisitor { cx, self_ty };
154
155             visitor.visit_ty(&impl_hir_ty);
156         }
157     }
158 }
159
160 impl<'tcx> LateLintPass<'tcx> for UseSelf {
161     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
162         if in_external_macro(cx.sess(), item.span) {
163             return;
164         }
165         if_chain! {
166             if let ItemKind::Impl{ self_ty: ref item_type, items: refs, .. } = item.kind;
167             if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.kind;
168             then {
169                 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
170                 let should_check = parameters.as_ref().map_or(
171                     true,
172                     |params| !params.parenthesized
173                         &&!params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
174                 );
175
176                 if should_check {
177                     let visitor = &mut UseSelfVisitor {
178                         item_path,
179                         cx,
180                     };
181                     let impl_def_id = cx.tcx.hir().local_def_id(item.hir_id);
182                     let impl_trait_ref = cx.tcx.impl_trait_ref(impl_def_id);
183
184                     if let Some(impl_trait_ref) = impl_trait_ref {
185                         for impl_item_ref in refs {
186                             let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
187                             if let ImplItemKind::Fn(FnSig{ decl: impl_decl, .. }, impl_body_id)
188                                     = &impl_item.kind {
189                                 check_trait_method_impl_decl(cx, impl_item, impl_decl, impl_trait_ref);
190
191                                 let body = cx.tcx.hir().body(*impl_body_id);
192                                 visitor.visit_body(body);
193                             } else {
194                                 visitor.visit_impl_item(impl_item);
195                             }
196                         }
197                     } else {
198                         for impl_item_ref in refs {
199                             let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
200                             visitor.visit_impl_item(impl_item);
201                         }
202                     }
203                 }
204             }
205         }
206     }
207 }
208
209 struct UseSelfVisitor<'a, 'tcx> {
210     item_path: &'a Path<'a>,
211     cx: &'a LateContext<'tcx>,
212 }
213
214 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
215     type Map = Map<'tcx>;
216
217     fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
218         if !path.segments.iter().any(|p| p.ident.span.is_dummy()) {
219             if path.segments.len() >= 2 {
220                 let last_but_one = &path.segments[path.segments.len() - 2];
221                 if last_but_one.ident.name != kw::SelfUpper {
222                     let enum_def_id = match path.res {
223                         Res::Def(DefKind::Variant, variant_def_id) => self.cx.tcx.parent(variant_def_id),
224                         Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), ctor_def_id) => {
225                             let variant_def_id = self.cx.tcx.parent(ctor_def_id);
226                             variant_def_id.and_then(|def_id| self.cx.tcx.parent(def_id))
227                         },
228                         _ => None,
229                     };
230
231                     if self.item_path.res.opt_def_id() == enum_def_id {
232                         span_use_self_lint(self.cx, path, Some(last_but_one));
233                     }
234                 }
235             }
236
237             if path.segments.last().expect(SEGMENTS_MSG).ident.name != kw::SelfUpper {
238                 if self.item_path.res == path.res {
239                     span_use_self_lint(self.cx, path, None);
240                 } else if let Res::Def(DefKind::Ctor(def::CtorOf::Struct, _), ctor_def_id) = path.res {
241                     if self.item_path.res.opt_def_id() == self.cx.tcx.parent(ctor_def_id) {
242                         span_use_self_lint(self.cx, path, None);
243                     }
244                 }
245             }
246         }
247
248         walk_path(self, path);
249     }
250
251     fn visit_item(&mut self, item: &'tcx Item<'_>) {
252         match item.kind {
253             ItemKind::Use(..)
254             | ItemKind::Static(..)
255             | ItemKind::Enum(..)
256             | ItemKind::Struct(..)
257             | ItemKind::Union(..)
258             | ItemKind::Impl { .. }
259             | ItemKind::Fn(..) => {
260                 // Don't check statements that shadow `Self` or where `Self` can't be used
261             },
262             _ => walk_item(self, item),
263         }
264     }
265
266     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
267         NestedVisitorMap::All(self.cx.tcx.hir())
268     }
269 }