1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
10 use crate::utils::{in_macro, span_lint_and_sugg};
11 use if_chain::if_chain;
12 use rustc::hir::def::{CtorKind, Def};
13 use rustc::hir::intravisit::{walk_path, walk_ty, NestedVisitorMap, Visitor};
15 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
17 use rustc::{declare_tool_lint, lint_array};
18 use rustc_errors::Applicability;
19 use syntax::ast::NodeId;
20 use syntax_pos::symbol::keywords::SelfUpper;
22 /// **What it does:** Checks for unnecessary repetition of structure name when a
23 /// replacement with `Self` is applicable.
25 /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
27 /// feels inconsistent.
29 /// **Known problems:**
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)
47 /// fn new() -> Self {
52 declare_clippy_lint! {
55 "Unnecessary structure name repetition whereas `Self` is applicable"
58 #[derive(Copy, Clone, Default)]
61 impl LintPass for UseSelf {
62 fn get_lints(&self) -> LintArray {
67 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
69 fn span_use_self_lint(cx: &LateContext<'_, '_>, path: &Path) {
74 "unnecessary structure name repetition",
75 "use the applicable keyword",
77 Applicability::MachineApplicable,
81 struct TraitImplTyVisitor<'a, 'tcx: 'a> {
82 item_type: ty::Ty<'tcx>,
83 cx: &'a LateContext<'a, 'tcx>,
84 trait_type_walker: ty::walk::TypeWalker<'tcx>,
85 impl_type_walker: ty::walk::TypeWalker<'tcx>,
88 impl<'a, 'tcx> Visitor<'tcx> for TraitImplTyVisitor<'a, 'tcx> {
89 fn visit_ty(&mut self, t: &'tcx Ty) {
90 let trait_ty = self.trait_type_walker.next();
91 let impl_ty = self.impl_type_walker.next();
93 if let TyKind::Path(QPath::Resolved(_, path)) = &t.node {
94 // The implementation and trait types don't match which means that
95 // the concrete type was specified by the implementation
96 if impl_ty != trait_ty {
97 if let Some(impl_ty) = impl_ty {
98 if self.item_type == impl_ty {
99 let is_self_ty = if let def::Def::SelfTy(..) = path.def {
106 span_use_self_lint(self.cx, path);
116 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
117 NestedVisitorMap::None
121 fn check_trait_method_impl_decl<'a, 'tcx: 'a>(
122 cx: &'a LateContext<'a, 'tcx>,
123 item_type: ty::Ty<'tcx>,
124 impl_item: &ImplItem,
125 impl_decl: &'tcx FnDecl,
126 impl_trait_ref: &ty::TraitRef<'_>,
128 let trait_method = cx
130 .associated_items(impl_trait_ref.def_id)
132 assoc_item.kind == ty::AssociatedKind::Method
135 .hygienic_eq(impl_item.ident, assoc_item.ident, impl_trait_ref.def_id)
137 .expect("impl method matches a trait method");
139 let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
140 let trait_method_sig = cx.tcx.erase_late_bound_regions(&trait_method_sig);
142 let impl_method_def_id = cx.tcx.hir().local_def_id(impl_item.id);
143 let impl_method_sig = cx.tcx.fn_sig(impl_method_def_id);
144 let impl_method_sig = cx.tcx.erase_late_bound_regions(&impl_method_sig);
146 let output_ty = if let FunctionRetTy::Return(ty) = &impl_decl.output {
152 // `impl_decl_ty` (of type `hir::Ty`) represents the type declared in the signature.
153 // `impl_ty` (of type `ty:TyS`) is the concrete type that the compiler has determined for
154 // that declaration. We use `impl_decl_ty` to see if the type was declared as `Self`
155 // and use `impl_ty` to check its concrete type.
156 for (impl_decl_ty, (impl_ty, trait_ty)) in impl_decl.inputs.iter().chain(output_ty).zip(
160 .zip(trait_method_sig.inputs_and_output),
162 let mut visitor = TraitImplTyVisitor {
165 trait_type_walker: trait_ty.walk(),
166 impl_type_walker: impl_ty.walk(),
169 visitor.visit_ty(&impl_decl_ty);
173 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UseSelf {
174 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
175 if in_macro(item.span) {
179 if let ItemKind::Impl(.., ref item_type, ref refs) = item.node;
180 if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.node;
182 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
183 let should_check = if let Some(ref params) = *parameters {
184 !params.parenthesized && !params.args.iter().any(|arg| match arg {
185 GenericArg::Lifetime(_) => true,
186 GenericArg::Type(_) => false,
193 let visitor = &mut UseSelfVisitor {
197 let impl_def_id = cx.tcx.hir().local_def_id(item.id);
198 let impl_trait_ref = cx.tcx.impl_trait_ref(impl_def_id);
200 if let Some(impl_trait_ref) = impl_trait_ref {
201 for impl_item_ref in refs {
202 let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
203 if let ImplItemKind::Method(MethodSig{ decl: impl_decl, .. }, impl_body_id)
205 let item_type = cx.tcx.type_of(impl_def_id);
206 check_trait_method_impl_decl(cx, item_type, impl_item, impl_decl, &impl_trait_ref);
208 let body = cx.tcx.hir().body(*impl_body_id);
209 visitor.visit_body(body);
211 visitor.visit_impl_item(impl_item);
215 for impl_item_ref in refs {
216 let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
217 visitor.visit_impl_item(impl_item);
226 struct UseSelfVisitor<'a, 'tcx: 'a> {
228 cx: &'a LateContext<'a, 'tcx>,
231 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
232 fn visit_path(&mut self, path: &'tcx Path, _id: HirId) {
233 if path.segments.last().expect(SEGMENTS_MSG).ident.name != SelfUpper.name() {
234 if self.item_path.def == path.def {
235 span_use_self_lint(self.cx, path);
236 } else if let Def::StructCtor(ctor_did, CtorKind::Fn) = path.def {
237 if self.item_path.def.opt_def_id() == self.cx.tcx.parent_def_id(ctor_did) {
238 span_use_self_lint(self.cx, path);
242 walk_path(self, path);
245 fn visit_use(&mut self, _path: &'tcx Path, _id: NodeId, _hir_id: HirId) {
246 // Don't check use statements
249 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
250 NestedVisitorMap::All(&self.cx.tcx.hir())