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