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