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