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