]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/use_self.rs
Document 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::{in_macro, span_lint_and_sugg};
11 use if_chain::if_chain;
12 use rustc::hir::intravisit::{walk_path, walk_ty, NestedVisitorMap, Visitor};
13 use rustc::hir::*;
14 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use rustc::ty;
16 use rustc::{declare_tool_lint, lint_array};
17 use rustc_errors::Applicability;
18 use syntax::ast::NodeId;
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 /// - Does not trigger within locally defined macros (#2098)
30 /// - False positive when using associated types (#2843)
31 /// - False positives in some situations when using generics (#3410)
32 /// - False positive when type from outer function can't be used (#3463)
33 /// - Does not diagnose tuple structs (#3498)
34 /// - Does not trigger in lifetimed struct
35 ///
36 /// **Example:**
37 /// ```rust
38 /// struct Foo {}
39 /// impl Foo {
40 ///     fn new() -> Foo {
41 ///         Foo {}
42 ///     }
43 /// }
44 /// ```
45 /// could be
46 /// ```rust
47 /// struct Foo {}
48 /// impl Foo {
49 ///     fn new() -> Self {
50 ///         Self {}
51 ///     }
52 /// }
53 /// ```
54 declare_clippy_lint! {
55     pub USE_SELF,
56     pedantic,
57     "Unnecessary structure name repetition whereas `Self` is applicable"
58 }
59
60 #[derive(Copy, Clone, Default)]
61 pub struct UseSelf;
62
63 impl LintPass for UseSelf {
64     fn get_lints(&self) -> LintArray {
65         lint_array!(USE_SELF)
66     }
67 }
68
69 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
70
71 fn span_use_self_lint(cx: &LateContext<'_, '_>, path: &Path) {
72     span_lint_and_sugg(
73         cx,
74         USE_SELF,
75         path.span,
76         "unnecessary structure name repetition",
77         "use the applicable keyword",
78         "Self".to_owned(),
79         Applicability::MachineApplicable,
80     );
81 }
82
83 struct TraitImplTyVisitor<'a, 'tcx: 'a> {
84     item_type: ty::Ty<'tcx>,
85     cx: &'a LateContext<'a, 'tcx>,
86     trait_type_walker: ty::walk::TypeWalker<'tcx>,
87     impl_type_walker: ty::walk::TypeWalker<'tcx>,
88 }
89
90 impl<'a, 'tcx> Visitor<'tcx> for TraitImplTyVisitor<'a, 'tcx> {
91     fn visit_ty(&mut self, t: &'tcx Ty) {
92         let trait_ty = self.trait_type_walker.next();
93         let impl_ty = self.impl_type_walker.next();
94
95         if let TyKind::Path(QPath::Resolved(_, path)) = &t.node {
96             // The implementation and trait types don't match which means that
97             // the concrete type was specified by the implementation
98             if impl_ty != trait_ty {
99                 if let Some(impl_ty) = impl_ty {
100                     if self.item_type == impl_ty {
101                         let is_self_ty = if let def::Def::SelfTy(..) = path.def {
102                             true
103                         } else {
104                             false
105                         };
106
107                         if !is_self_ty {
108                             span_use_self_lint(self.cx, path);
109                         }
110                     }
111                 }
112             }
113         }
114
115         walk_ty(self, t)
116     }
117
118     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
119         NestedVisitorMap::None
120     }
121 }
122
123 fn check_trait_method_impl_decl<'a, 'tcx: 'a>(
124     cx: &'a LateContext<'a, 'tcx>,
125     item_type: ty::Ty<'tcx>,
126     impl_item: &ImplItem,
127     impl_decl: &'tcx FnDecl,
128     impl_trait_ref: &ty::TraitRef<'_>,
129 ) {
130     let trait_method = cx
131         .tcx
132         .associated_items(impl_trait_ref.def_id)
133         .find(|assoc_item| {
134             assoc_item.kind == ty::AssociatedKind::Method
135                 && cx
136                     .tcx
137                     .hygienic_eq(impl_item.ident, assoc_item.ident, impl_trait_ref.def_id)
138         })
139         .expect("impl method matches a trait method");
140
141     let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
142     let trait_method_sig = cx.tcx.erase_late_bound_regions(&trait_method_sig);
143
144     let impl_method_def_id = cx.tcx.hir().local_def_id(impl_item.id);
145     let impl_method_sig = cx.tcx.fn_sig(impl_method_def_id);
146     let impl_method_sig = cx.tcx.erase_late_bound_regions(&impl_method_sig);
147
148     let output_ty = if let FunctionRetTy::Return(ty) = &impl_decl.output {
149         Some(&**ty)
150     } else {
151         None
152     };
153
154     // `impl_decl_ty` (of type `hir::Ty`) represents the type declared in the signature.
155     // `impl_ty` (of type `ty:TyS`) is the concrete type that the compiler has determined for
156     // that declaration.  We use `impl_decl_ty` to see if the type was declared as `Self`
157     // and use `impl_ty` to check its concrete type.
158     for (impl_decl_ty, (impl_ty, trait_ty)) in impl_decl.inputs.iter().chain(output_ty).zip(
159         impl_method_sig
160             .inputs_and_output
161             .iter()
162             .zip(trait_method_sig.inputs_and_output),
163     ) {
164         let mut visitor = TraitImplTyVisitor {
165             cx,
166             item_type,
167             trait_type_walker: trait_ty.walk(),
168             impl_type_walker: impl_ty.walk(),
169         };
170
171         visitor.visit_ty(&impl_decl_ty);
172     }
173 }
174
175 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UseSelf {
176     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
177         if in_macro(item.span) {
178             return;
179         }
180         if_chain! {
181             if let ItemKind::Impl(.., ref item_type, ref refs) = item.node;
182             if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.node;
183             then {
184                 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
185                 let should_check = if let Some(ref params) = *parameters {
186                     !params.parenthesized && !params.args.iter().any(|arg| match arg {
187                         GenericArg::Lifetime(_) => true,
188                         GenericArg::Type(_) => false,
189                     })
190                 } else {
191                     true
192                 };
193
194                 if should_check {
195                     let visitor = &mut UseSelfVisitor {
196                         item_path,
197                         cx,
198                     };
199                     let impl_def_id = cx.tcx.hir().local_def_id(item.id);
200                     let impl_trait_ref = cx.tcx.impl_trait_ref(impl_def_id);
201
202                     if let Some(impl_trait_ref) = impl_trait_ref {
203                         for impl_item_ref in refs {
204                             let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
205                             if let ImplItemKind::Method(MethodSig{ decl: impl_decl, .. }, impl_body_id)
206                                     = &impl_item.node {
207                                 let item_type = cx.tcx.type_of(impl_def_id);
208                                 check_trait_method_impl_decl(cx, item_type, impl_item, impl_decl, &impl_trait_ref);
209
210                                 let body = cx.tcx.hir().body(*impl_body_id);
211                                 visitor.visit_body(body);
212                             } else {
213                                 visitor.visit_impl_item(impl_item);
214                             }
215                         }
216                     } else {
217                         for impl_item_ref in refs {
218                             let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
219                             visitor.visit_impl_item(impl_item);
220                         }
221                     }
222                 }
223             }
224         }
225     }
226 }
227
228 struct UseSelfVisitor<'a, 'tcx: 'a> {
229     item_path: &'a Path,
230     cx: &'a LateContext<'a, 'tcx>,
231 }
232
233 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
234     fn visit_path(&mut self, path: &'tcx Path, _id: HirId) {
235         if self.item_path.def == path.def && path.segments.last().expect(SEGMENTS_MSG).ident.name != SelfUpper.name() {
236             span_use_self_lint(self.cx, path);
237         }
238
239         walk_path(self, path);
240     }
241
242     fn visit_use(&mut self, _path: &'tcx Path, _id: NodeId, _hir_id: HirId) {
243         // Don't check use statements
244     }
245
246     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
247         NestedVisitorMap::All(&self.cx.tcx.hir())
248     }
249 }