]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/use_self.rs
Auto merge of #4229 - euclio:lint-doc-generation-fix, r=flip1995
[rust.git] / clippy_lints / src / use_self.rs
1 use if_chain::if_chain;
2 use rustc::hir;
3 use rustc::hir::def::{CtorKind, DefKind, Res};
4 use rustc::hir::intravisit::{walk_item, walk_path, walk_ty, NestedVisitorMap, Visitor};
5 use rustc::hir::*;
6 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
7 use rustc::ty;
8 use rustc::ty::{DefIdTree, Ty};
9 use rustc::{declare_lint_pass, declare_tool_lint};
10 use rustc_errors::Applicability;
11 use syntax_pos::symbol::kw;
12
13 use crate::utils::span_lint_and_sugg;
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for unnecessary repetition of structure name when a
17     /// replacement with `Self` is applicable.
18     ///
19     /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
20     /// name
21     /// feels inconsistent.
22     ///
23     /// **Known problems:**
24     /// - False positive when using associated types (#2843)
25     /// - False positives in some situations when using generics (#3410)
26     ///
27     /// **Example:**
28     /// ```rust
29     /// struct Foo {}
30     /// impl Foo {
31     ///     fn new() -> Foo {
32     ///         Foo {}
33     ///     }
34     /// }
35     /// ```
36     /// could be
37     /// ```rust
38     /// struct Foo {}
39     /// impl Foo {
40     ///     fn new() -> Self {
41     ///         Self {}
42     ///     }
43     /// }
44     /// ```
45     pub USE_SELF,
46     pedantic,
47     "Unnecessary structure name repetition whereas `Self` is applicable"
48 }
49
50 declare_lint_pass!(UseSelf => [USE_SELF]);
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     // Path segments only include actual path, no methods or fields.
56     let last_path_span = path.segments.last().expect(SEGMENTS_MSG).ident.span;
57     // Only take path up to the end of last_path_span.
58     let span = path.span.with_hi(last_path_span.hi());
59
60     span_lint_and_sugg(
61         cx,
62         USE_SELF,
63         span,
64         "unnecessary structure name repetition",
65         "use the applicable keyword",
66         "Self".to_owned(),
67         Applicability::MachineApplicable,
68     );
69 }
70
71 struct TraitImplTyVisitor<'a, 'tcx> {
72     item_type: Ty<'tcx>,
73     cx: &'a LateContext<'a, 'tcx>,
74     trait_type_walker: ty::walk::TypeWalker<'tcx>,
75     impl_type_walker: ty::walk::TypeWalker<'tcx>,
76 }
77
78 impl<'a, 'tcx> Visitor<'tcx> for TraitImplTyVisitor<'a, 'tcx> {
79     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
80         let trait_ty = self.trait_type_walker.next();
81         let impl_ty = self.impl_type_walker.next();
82
83         if let TyKind::Path(QPath::Resolved(_, path)) = &t.node {
84             // The implementation and trait types don't match which means that
85             // the concrete type was specified by the implementation
86             if impl_ty != trait_ty {
87                 if let Some(impl_ty) = impl_ty {
88                     if self.item_type == impl_ty {
89                         let is_self_ty = if let def::Res::SelfTy(..) = path.res {
90                             true
91                         } else {
92                             false
93                         };
94
95                         if !is_self_ty {
96                             span_use_self_lint(self.cx, path);
97                         }
98                     }
99                 }
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>(
112     cx: &'a LateContext<'a, 'tcx>,
113     item_type: Ty<'tcx>,
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::AssocKind::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.hir_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_type,
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_external_macro(cx.sess(), 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                         _ => 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.hir_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                                 let item_type = cx.tcx.type_of(impl_def_id);
196                                 check_trait_method_impl_decl(cx, item_type, impl_item, impl_decl, &impl_trait_ref);
197
198                                 let body = cx.tcx.hir().body(*impl_body_id);
199                                 visitor.visit_body(body);
200                             } else {
201                                 visitor.visit_impl_item(impl_item);
202                             }
203                         }
204                     } else {
205                         for impl_item_ref in refs {
206                             let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
207                             visitor.visit_impl_item(impl_item);
208                         }
209                     }
210                 }
211             }
212         }
213     }
214 }
215
216 struct UseSelfVisitor<'a, 'tcx> {
217     item_path: &'a Path,
218     cx: &'a LateContext<'a, 'tcx>,
219 }
220
221 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
222     fn visit_path(&mut self, path: &'tcx Path, _id: HirId) {
223         if path.segments.last().expect(SEGMENTS_MSG).ident.name != kw::SelfUpper {
224             if self.item_path.res == path.res {
225                 span_use_self_lint(self.cx, path);
226             } else if let Res::Def(DefKind::Ctor(def::CtorOf::Struct, CtorKind::Fn), ctor_did) = path.res {
227                 if self.item_path.res.opt_def_id() == self.cx.tcx.parent(ctor_did) {
228                     span_use_self_lint(self.cx, path);
229                 }
230             }
231         }
232         walk_path(self, path);
233     }
234
235     fn visit_item(&mut self, item: &'tcx Item) {
236         match item.node {
237             ItemKind::Use(..)
238             | ItemKind::Static(..)
239             | ItemKind::Enum(..)
240             | ItemKind::Struct(..)
241             | ItemKind::Union(..)
242             | ItemKind::Impl(..)
243             | ItemKind::Fn(..) => {
244                 // Don't check statements that shadow `Self` or where `Self` can't be used
245             },
246             _ => walk_item(self, item),
247         }
248     }
249
250     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
251         NestedVisitorMap::All(&self.cx.tcx.hir())
252     }
253 }