]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/use_self.rs
Update known problems
[rust.git] / clippy_lints / src / use_self.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::utils::span_lint_and_sugg;
11 use if_chain::if_chain;
12 use rustc::hir::def::{CtorKind, Def};
13 use rustc::hir::intravisit::{walk_item, walk_path, walk_ty, NestedVisitorMap, Visitor};
14 use rustc::hir::*;
15 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
16 use rustc::ty;
17 use rustc::{declare_tool_lint, lint_array};
18 use rustc_errors::Applicability;
19 use syntax_pos::symbol::keywords::SelfUpper;
20
21 /// **What it does:** Checks for unnecessary repetition of structure name when a
22 /// replacement with `Self` is applicable.
23 ///
24 /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
25 /// name
26 /// feels inconsistent.
27 ///
28 /// **Known problems:**
29 /// - False positive when using associated types (#2843)
30 /// - False positives in some situations when using generics (#3410)
31 ///
32 /// **Example:**
33 /// ```rust
34 /// struct Foo {}
35 /// impl Foo {
36 ///     fn new() -> Foo {
37 ///         Foo {}
38 ///     }
39 /// }
40 /// ```
41 /// could be
42 /// ```rust
43 /// struct Foo {}
44 /// impl Foo {
45 ///     fn new() -> Self {
46 ///         Self {}
47 ///     }
48 /// }
49 /// ```
50 declare_clippy_lint! {
51     pub USE_SELF,
52     pedantic,
53     "Unnecessary structure name repetition whereas `Self` is applicable"
54 }
55
56 #[derive(Copy, Clone, Default)]
57 pub struct UseSelf;
58
59 impl LintPass for UseSelf {
60     fn get_lints(&self) -> LintArray {
61         lint_array!(USE_SELF)
62     }
63 }
64
65 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
66
67 fn span_use_self_lint(cx: &LateContext<'_, '_>, path: &Path) {
68     span_lint_and_sugg(
69         cx,
70         USE_SELF,
71         path.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: 'a> {
80     item_type: ty::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 Ty) {
88         let trait_ty = self.trait_type_walker.next();
89         let impl_ty = self.impl_type_walker.next();
90
91         if let TyKind::Path(QPath::Resolved(_, path)) = &t.node {
92             // The implementation and trait types don't match which means that
93             // the concrete type was specified by the implementation
94             if impl_ty != trait_ty {
95                 if let Some(impl_ty) = impl_ty {
96                     if self.item_type == impl_ty {
97                         let is_self_ty = if let def::Def::SelfTy(..) = path.def {
98                             true
99                         } else {
100                             false
101                         };
102
103                         if !is_self_ty {
104                             span_use_self_lint(self.cx, path);
105                         }
106                     }
107                 }
108             }
109         }
110
111         walk_ty(self, t)
112     }
113
114     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
115         NestedVisitorMap::None
116     }
117 }
118
119 fn check_trait_method_impl_decl<'a, 'tcx: 'a>(
120     cx: &'a LateContext<'a, 'tcx>,
121     item_type: ty::Ty<'tcx>,
122     impl_item: &ImplItem,
123     impl_decl: &'tcx FnDecl,
124     impl_trait_ref: &ty::TraitRef<'_>,
125 ) {
126     let trait_method = cx
127         .tcx
128         .associated_items(impl_trait_ref.def_id)
129         .find(|assoc_item| {
130             assoc_item.kind == ty::AssociatedKind::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.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(.., ref item_type, ref refs) = item.node;
178             if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.node;
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                         GenericArg::Type(_) => 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.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(MethodSig{ decl: impl_decl, .. }, impl_body_id)
202                                     = &impl_item.node {
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: 'a> {
225     item_path: &'a Path,
226     cx: &'a LateContext<'a, 'tcx>,
227 }
228
229 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
230     fn visit_path(&mut self, path: &'tcx Path, _id: HirId) {
231         if path.segments.last().expect(SEGMENTS_MSG).ident.name != SelfUpper.name() {
232             if self.item_path.def == path.def {
233                 span_use_self_lint(self.cx, path);
234             } else if let Def::StructCtor(ctor_did, CtorKind::Fn) = path.def {
235                 if self.item_path.def.opt_def_id() == self.cx.tcx.parent_def_id(ctor_did) {
236                     span_use_self_lint(self.cx, path);
237                 }
238             }
239         }
240         walk_path(self, path);
241     }
242
243     fn visit_item(&mut self, item: &'tcx Item) {
244         match item.node {
245             ItemKind::Use(..)
246             | ItemKind::Static(..)
247             | ItemKind::Enum(..)
248             | ItemKind::Struct(..)
249             | ItemKind::Union(..) => {
250                 // Don't check statements that shadow `Self` or where `Self` can't be used
251             },
252             _ => walk_item(self, item),
253         }
254     }
255
256     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
257         NestedVisitorMap::All(&self.cx.tcx.hir())
258     }
259 }