]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/use_self.rs
Fix use_self regressions
[rust.git] / clippy_lints / src / use_self.rs
1 use crate::utils::{in_macro, span_lint_and_then};
2 use rustc::hir::intravisit::{walk_path, walk_ty, NestedVisitorMap, Visitor};
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::ty;
6 use syntax::ast::NodeId;
7 use syntax_pos::symbol::keywords::SelfType;
8
9 /// **What it does:** Checks for unnecessary repetition of structure name when a
10 /// replacement with `Self` is applicable.
11 ///
12 /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
13 /// name
14 /// feels inconsistent.
15 ///
16 /// **Known problems:** None.
17 ///
18 /// **Example:**
19 /// ```rust
20 /// struct Foo {}
21 /// impl Foo {
22 ///     fn new() -> Foo {
23 ///         Foo {}
24 ///     }
25 /// }
26 /// ```
27 /// could be
28 /// ```
29 /// struct Foo {}
30 /// impl Foo {
31 ///     fn new() -> Self {
32 ///         Self {}
33 ///     }
34 /// }
35 /// ```
36 declare_clippy_lint! {
37     pub USE_SELF,
38     pedantic,
39     "Unnecessary structure name repetition whereas `Self` is applicable"
40 }
41
42 #[derive(Copy, Clone, Default)]
43 pub struct UseSelf;
44
45 impl LintPass for UseSelf {
46     fn get_lints(&self) -> LintArray {
47         lint_array!(USE_SELF)
48     }
49 }
50
51 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
52
53 fn span_use_self_lint(cx: &LateContext, path: &Path) {
54     span_lint_and_then(cx, USE_SELF, path.span, "unnecessary structure name repetition", |db| {
55         db.span_suggestion(path.span, "use the applicable keyword", "Self".to_owned());
56     });
57 }
58
59 struct TraitImplTyVisitor<'a, 'tcx: 'a> {
60     item_path: &'a Path,
61     cx: &'a LateContext<'a, 'tcx>,
62     trait_type_walker: ty::walk::TypeWalker<'tcx>,
63     impl_type_walker: ty::walk::TypeWalker<'tcx>,
64 }
65
66 impl<'a, 'tcx> Visitor<'tcx> for TraitImplTyVisitor<'a, 'tcx> {
67     fn visit_ty(&mut self, t: &'tcx Ty) {
68         let trait_ty = self.trait_type_walker.next();
69         let impl_ty = self.impl_type_walker.next();
70
71         if let TyKind::Path(QPath::Resolved(_, path)) = &t.node {
72             if self.item_path.def == path.def {
73                 let is_self_ty = if let def::Def::SelfTy(..) = path.def {
74                     true
75                 } else {
76                     false
77                 };
78
79                 if !is_self_ty && impl_ty != trait_ty {
80                     // The implementation and trait types don't match which means that
81                     // the concrete type was specified by the implementation but
82                     // it didn't use `Self`
83                     span_use_self_lint(self.cx, path);
84                 }
85             }
86         }
87         walk_ty(self, t)
88     }
89
90     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
91         NestedVisitorMap::None
92     }
93 }
94
95 fn check_trait_method_impl_decl<'a, 'tcx: 'a>(
96     cx: &'a LateContext<'a, 'tcx>,
97     item_path: &'a Path,
98     impl_item: &ImplItem,
99     impl_decl: &'tcx FnDecl,
100     impl_trait_ref: &ty::TraitRef,
101 ) {
102     let trait_method = cx
103         .tcx
104         .associated_items(impl_trait_ref.def_id)
105         .find(|assoc_item| {
106             assoc_item.kind == ty::AssociatedKind::Method
107                 && cx
108                     .tcx
109                     .hygienic_eq(impl_item.ident, assoc_item.ident, impl_trait_ref.def_id)
110         })
111         .expect("impl method matches a trait method");
112
113     let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
114     let trait_method_sig = cx.tcx.erase_late_bound_regions(&trait_method_sig);
115
116     let impl_method_def_id = cx.tcx.hir.local_def_id(impl_item.id);
117     let impl_method_sig = cx.tcx.fn_sig(impl_method_def_id);
118     let impl_method_sig = cx.tcx.erase_late_bound_regions(&impl_method_sig);
119
120     let output_ty = if let FunctionRetTy::Return(ty) = &impl_decl.output {
121         Some(&**ty)
122     } else {
123         None
124     };
125
126     for (impl_decl_ty, (impl_ty, trait_ty)) in impl_decl.inputs.iter().chain(output_ty).zip(
127         impl_method_sig
128             .inputs_and_output
129             .iter()
130             .zip(trait_method_sig.inputs_and_output),
131     ) {
132         let mut visitor = TraitImplTyVisitor {
133             cx,
134             item_path,
135             trait_type_walker: trait_ty.walk(),
136             impl_type_walker: impl_ty.walk(),
137         };
138
139         visitor.visit_ty(&impl_decl_ty);
140     }
141 }
142
143 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UseSelf {
144     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
145         if in_macro(item.span) {
146             return;
147         }
148         if_chain! {
149             if let ItemKind::Impl(.., ref item_type, ref refs) = item.node;
150             if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.node;
151             then {
152                 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
153                 let should_check = if let Some(ref params) = *parameters {
154                     !params.parenthesized && !params.args.iter().any(|arg| match arg {
155                         GenericArg::Lifetime(_) => true,
156                         GenericArg::Type(_) => false,
157                     })
158                 } else {
159                     true
160                 };
161
162                 if should_check {
163                     let visitor = &mut UseSelfVisitor {
164                         item_path,
165                         cx,
166                     };
167                     let impl_def_id = cx.tcx.hir.local_def_id(item.id);
168                     let impl_trait_ref = cx.tcx.impl_trait_ref(impl_def_id);
169
170                     if let Some(impl_trait_ref) = impl_trait_ref {
171                         for impl_item_ref in refs {
172                             let impl_item = cx.tcx.hir.impl_item(impl_item_ref.id);
173                             if let ImplItemKind::Method(MethodSig{ decl: impl_decl, .. }, impl_body_id)
174                                     = &impl_item.node {
175                                 check_trait_method_impl_decl(cx, item_path, impl_item, impl_decl, &impl_trait_ref);
176                                 let body = cx.tcx.hir.body(*impl_body_id);
177                                 visitor.visit_body(body);
178                             } else {
179                                 visitor.visit_impl_item(impl_item);
180                             }
181                         }
182                     } else {
183                         for impl_item_ref in refs {
184                             let impl_item = cx.tcx.hir.impl_item(impl_item_ref.id);
185                             visitor.visit_impl_item(impl_item);
186                         }
187                     }
188                 }
189             }
190         }
191     }
192 }
193
194 struct UseSelfVisitor<'a, 'tcx: 'a> {
195     item_path: &'a Path,
196     cx: &'a LateContext<'a, 'tcx>,
197 }
198
199 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
200     fn visit_path(&mut self, path: &'tcx Path, _id: NodeId) {
201         if self.item_path.def == path.def && path.segments.last().expect(SEGMENTS_MSG).ident.name != SelfType.name() {
202             span_use_self_lint(self.cx, path);
203         }
204
205         walk_path(self, path);
206     }
207
208     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
209         NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir)
210     }
211 }