1 use crate::utils::span_lint_and_sugg;
2 use if_chain::if_chain;
3 use rustc::hir::def::{CtorKind, Def};
4 use rustc::hir::intravisit::{walk_item, walk_path, walk_ty, NestedVisitorMap, Visitor};
6 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
8 use rustc::{declare_tool_lint, lint_array};
9 use rustc_errors::Applicability;
10 use syntax_pos::symbol::keywords::SelfUpper;
12 /// **What it does:** Checks for unnecessary repetition of structure name when a
13 /// replacement with `Self` is applicable.
15 /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
17 /// feels inconsistent.
19 /// **Known problems:**
20 /// - False positive when using associated types (#2843)
21 /// - False positives in some situations when using generics (#3410)
36 /// fn new() -> Self {
41 declare_clippy_lint! {
44 "Unnecessary structure name repetition whereas `Self` is applicable"
47 #[derive(Copy, Clone, Default)]
50 impl LintPass for UseSelf {
51 fn get_lints(&self) -> LintArray {
56 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
58 fn span_use_self_lint(cx: &LateContext<'_, '_>, path: &Path) {
59 // path segments only include actual path, no methods or fields
60 let last_path_span = path.segments.last().expect(SEGMENTS_MSG).ident.span;
61 // `to()` doesn't shorten span, so we shorten it with `until(..)`
62 // and then include it with `to(..)`
63 let span = path.span.with_hi(last_path_span.hi());
69 "unnecessary structure name repetition",
70 "use the applicable keyword",
72 Applicability::MachineApplicable,
76 struct TraitImplTyVisitor<'a, 'tcx: 'a> {
77 item_type: ty::Ty<'tcx>,
78 cx: &'a LateContext<'a, 'tcx>,
79 trait_type_walker: ty::walk::TypeWalker<'tcx>,
80 impl_type_walker: ty::walk::TypeWalker<'tcx>,
83 impl<'a, 'tcx> Visitor<'tcx> for TraitImplTyVisitor<'a, 'tcx> {
84 fn visit_ty(&mut self, t: &'tcx Ty) {
85 let trait_ty = self.trait_type_walker.next();
86 let impl_ty = self.impl_type_walker.next();
88 if let TyKind::Path(QPath::Resolved(_, path)) = &t.node {
89 // The implementation and trait types don't match which means that
90 // the concrete type was specified by the implementation
91 if impl_ty != trait_ty {
92 if let Some(impl_ty) = impl_ty {
93 if self.item_type == impl_ty {
94 let is_self_ty = if let def::Def::SelfTy(..) = path.def {
101 span_use_self_lint(self.cx, path);
111 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
112 NestedVisitorMap::None
116 fn check_trait_method_impl_decl<'a, 'tcx: 'a>(
117 cx: &'a LateContext<'a, 'tcx>,
118 item_type: ty::Ty<'tcx>,
119 impl_item: &ImplItem,
120 impl_decl: &'tcx FnDecl,
121 impl_trait_ref: &ty::TraitRef<'_>,
123 let trait_method = cx
125 .associated_items(impl_trait_ref.def_id)
127 assoc_item.kind == ty::AssociatedKind::Method
130 .hygienic_eq(impl_item.ident, assoc_item.ident, impl_trait_ref.def_id)
132 .expect("impl method matches a trait method");
134 let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
135 let trait_method_sig = cx.tcx.erase_late_bound_regions(&trait_method_sig);
137 let impl_method_def_id = cx.tcx.hir().local_def_id(impl_item.id);
138 let impl_method_sig = cx.tcx.fn_sig(impl_method_def_id);
139 let impl_method_sig = cx.tcx.erase_late_bound_regions(&impl_method_sig);
141 let output_ty = if let FunctionRetTy::Return(ty) = &impl_decl.output {
147 // `impl_decl_ty` (of type `hir::Ty`) represents the type declared in the signature.
148 // `impl_ty` (of type `ty:TyS`) is the concrete type that the compiler has determined for
149 // that declaration. We use `impl_decl_ty` to see if the type was declared as `Self`
150 // and use `impl_ty` to check its concrete type.
151 for (impl_decl_ty, (impl_ty, trait_ty)) in impl_decl.inputs.iter().chain(output_ty).zip(
155 .zip(trait_method_sig.inputs_and_output),
157 let mut visitor = TraitImplTyVisitor {
160 trait_type_walker: trait_ty.walk(),
161 impl_type_walker: impl_ty.walk(),
164 visitor.visit_ty(&impl_decl_ty);
168 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UseSelf {
169 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
170 if in_external_macro(cx.sess(), item.span) {
174 if let ItemKind::Impl(.., ref item_type, ref refs) = item.node;
175 if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.node;
177 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
178 let should_check = if let Some(ref params) = *parameters {
179 !params.parenthesized && !params.args.iter().any(|arg| match arg {
180 GenericArg::Lifetime(_) => true,
181 GenericArg::Type(_) => false,
188 let visitor = &mut UseSelfVisitor {
192 let impl_def_id = cx.tcx.hir().local_def_id(item.id);
193 let impl_trait_ref = cx.tcx.impl_trait_ref(impl_def_id);
195 if let Some(impl_trait_ref) = impl_trait_ref {
196 for impl_item_ref in refs {
197 let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
198 if let ImplItemKind::Method(MethodSig{ decl: impl_decl, .. }, impl_body_id)
200 let item_type = cx.tcx.type_of(impl_def_id);
201 check_trait_method_impl_decl(cx, item_type, impl_item, impl_decl, &impl_trait_ref);
203 let body = cx.tcx.hir().body(*impl_body_id);
204 visitor.visit_body(body);
206 visitor.visit_impl_item(impl_item);
210 for impl_item_ref in refs {
211 let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
212 visitor.visit_impl_item(impl_item);
221 struct UseSelfVisitor<'a, 'tcx: 'a> {
223 cx: &'a LateContext<'a, 'tcx>,
226 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
227 fn visit_path(&mut self, path: &'tcx Path, _id: HirId) {
228 if path.segments.last().expect(SEGMENTS_MSG).ident.name != SelfUpper.name() {
229 if self.item_path.def == path.def {
230 span_use_self_lint(self.cx, path);
231 } else if let Def::StructCtor(ctor_did, CtorKind::Fn) = path.def {
232 if self.item_path.def.opt_def_id() == self.cx.tcx.parent_def_id(ctor_did) {
233 span_use_self_lint(self.cx, path);
237 walk_path(self, path);
240 fn visit_item(&mut self, item: &'tcx Item) {
243 | ItemKind::Static(..)
245 | ItemKind::Struct(..)
246 | ItemKind::Union(..)
247 | ItemKind::Impl(..) => {
248 // Don't check statements that shadow `Self` or where `Self` can't be used
250 _ => walk_item(self, item),
254 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
255 NestedVisitorMap::All(&self.cx.tcx.hir())