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