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