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