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