]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/use_self.rs
Auto merge of #3901 - rail-rain:issue_1670, 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_tool_lint, lint_array};
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 #[derive(Copy, Clone, Default)]
50 pub struct UseSelf;
51
52 impl LintPass for UseSelf {
53     fn get_lints(&self) -> LintArray {
54         lint_array!(USE_SELF)
55     }
56
57     fn name(&self) -> &'static str {
58         "UseSelf"
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     // Path segments only include actual path, no methods or fields.
66     let last_path_span = path.segments.last().expect(SEGMENTS_MSG).ident.span;
67     // Only take path up to the end of last_path_span.
68     let span = path.span.with_hi(last_path_span.hi());
69
70     span_lint_and_sugg(
71         cx,
72         USE_SELF,
73         span,
74         "unnecessary structure name repetition",
75         "use the applicable keyword",
76         "Self".to_owned(),
77         Applicability::MachineApplicable,
78     );
79 }
80
81 struct TraitImplTyVisitor<'a, 'tcx: 'a> {
82     item_type: ty::Ty<'tcx>,
83     cx: &'a LateContext<'a, 'tcx>,
84     trait_type_walker: ty::walk::TypeWalker<'tcx>,
85     impl_type_walker: ty::walk::TypeWalker<'tcx>,
86 }
87
88 impl<'a, 'tcx> Visitor<'tcx> for TraitImplTyVisitor<'a, 'tcx> {
89     fn visit_ty(&mut self, t: &'tcx Ty) {
90         let trait_ty = self.trait_type_walker.next();
91         let impl_ty = self.impl_type_walker.next();
92
93         if let TyKind::Path(QPath::Resolved(_, path)) = &t.node {
94             // The implementation and trait types don't match which means that
95             // the concrete type was specified by the implementation
96             if impl_ty != trait_ty {
97                 if let Some(impl_ty) = impl_ty {
98                     if self.item_type == impl_ty {
99                         let is_self_ty = if let def::Def::SelfTy(..) = path.def {
100                             true
101                         } else {
102                             false
103                         };
104
105                         if !is_self_ty {
106                             span_use_self_lint(self.cx, path);
107                         }
108                     }
109                 }
110             }
111         }
112
113         walk_ty(self, t)
114     }
115
116     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
117         NestedVisitorMap::None
118     }
119 }
120
121 fn check_trait_method_impl_decl<'a, 'tcx: 'a>(
122     cx: &'a LateContext<'a, 'tcx>,
123     item_type: ty::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(|assoc_item| {
132             assoc_item.kind == ty::AssociatedKind::Method
133                 && cx
134                     .tcx
135                     .hygienic_eq(impl_item.ident, assoc_item.ident, impl_trait_ref.def_id)
136         })
137         .expect("impl method matches a trait method");
138
139     let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
140     let trait_method_sig = cx.tcx.erase_late_bound_regions(&trait_method_sig);
141
142     let impl_method_def_id = cx.tcx.hir().local_def_id_from_hir_id(impl_item.hir_id);
143     let impl_method_sig = cx.tcx.fn_sig(impl_method_def_id);
144     let impl_method_sig = cx.tcx.erase_late_bound_regions(&impl_method_sig);
145
146     let output_ty = if let FunctionRetTy::Return(ty) = &impl_decl.output {
147         Some(&**ty)
148     } else {
149         None
150     };
151
152     // `impl_decl_ty` (of type `hir::Ty`) represents the type declared in the signature.
153     // `impl_ty` (of type `ty:TyS`) is the concrete type that the compiler has determined for
154     // that declaration. We use `impl_decl_ty` to see if the type was declared as `Self`
155     // and use `impl_ty` to check its concrete type.
156     for (impl_decl_ty, (impl_ty, trait_ty)) in impl_decl.inputs.iter().chain(output_ty).zip(
157         impl_method_sig
158             .inputs_and_output
159             .iter()
160             .zip(trait_method_sig.inputs_and_output),
161     ) {
162         let mut visitor = TraitImplTyVisitor {
163             cx,
164             item_type,
165             trait_type_walker: trait_ty.walk(),
166             impl_type_walker: impl_ty.walk(),
167         };
168
169         visitor.visit_ty(&impl_decl_ty);
170     }
171 }
172
173 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UseSelf {
174     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
175         if in_external_macro(cx.sess(), item.span) {
176             return;
177         }
178         if_chain! {
179             if let ItemKind::Impl(.., ref item_type, ref refs) = item.node;
180             if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.node;
181             then {
182                 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
183                 let should_check = if let Some(ref params) = *parameters {
184                     !params.parenthesized && !params.args.iter().any(|arg| match arg {
185                         GenericArg::Lifetime(_) => true,
186                         _ => false,
187                     })
188                 } else {
189                     true
190                 };
191
192                 if should_check {
193                     let visitor = &mut UseSelfVisitor {
194                         item_path,
195                         cx,
196                     };
197                     let impl_def_id = cx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
198                     let impl_trait_ref = cx.tcx.impl_trait_ref(impl_def_id);
199
200                     if let Some(impl_trait_ref) = impl_trait_ref {
201                         for impl_item_ref in refs {
202                             let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
203                             if let ImplItemKind::Method(MethodSig{ decl: impl_decl, .. }, impl_body_id)
204                                     = &impl_item.node {
205                                 let item_type = cx.tcx.type_of(impl_def_id);
206                                 check_trait_method_impl_decl(cx, item_type, impl_item, impl_decl, &impl_trait_ref);
207
208                                 let body = cx.tcx.hir().body(*impl_body_id);
209                                 visitor.visit_body(body);
210                             } else {
211                                 visitor.visit_impl_item(impl_item);
212                             }
213                         }
214                     } else {
215                         for impl_item_ref in refs {
216                             let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
217                             visitor.visit_impl_item(impl_item);
218                         }
219                     }
220                 }
221             }
222         }
223     }
224 }
225
226 struct UseSelfVisitor<'a, 'tcx: 'a> {
227     item_path: &'a Path,
228     cx: &'a LateContext<'a, 'tcx>,
229 }
230
231 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
232     fn visit_path(&mut self, path: &'tcx Path, _id: HirId) {
233         if path.segments.last().expect(SEGMENTS_MSG).ident.name != SelfUpper.name() {
234             if self.item_path.def == path.def {
235                 span_use_self_lint(self.cx, path);
236             } else if let Def::Ctor(ctor_did, def::CtorOf::Struct, CtorKind::Fn) = path.def {
237                 if self.item_path.def.opt_def_id() == self.cx.tcx.parent(ctor_did) {
238                     span_use_self_lint(self.cx, path);
239                 }
240             }
241         }
242         walk_path(self, path);
243     }
244
245     fn visit_item(&mut self, item: &'tcx Item) {
246         match item.node {
247             ItemKind::Use(..)
248             | ItemKind::Static(..)
249             | ItemKind::Enum(..)
250             | ItemKind::Struct(..)
251             | ItemKind::Union(..)
252             | ItemKind::Impl(..)
253             | ItemKind::Fn(..) => {
254                 // Don't check statements that shadow `Self` or where `Self` can't be used
255             },
256             _ => walk_item(self, item),
257         }
258     }
259
260     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
261         NestedVisitorMap::All(&self.cx.tcx.hir())
262     }
263 }