1 use if_chain::if_chain;
3 use rustc::hir::def::{DefKind, Res};
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::ty::{DefIdTree, Ty};
9 use rustc::{declare_lint_pass, declare_tool_lint};
10 use rustc_errors::Applicability;
11 use syntax_pos::symbol::kw;
13 use crate::utils::span_lint_and_sugg;
15 declare_clippy_lint! {
16 /// **What it does:** Checks for unnecessary repetition of structure name when a
17 /// replacement with `Self` is applicable.
19 /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
21 /// feels inconsistent.
23 /// **Known problems:**
24 /// - False positive when using associated types (#2843)
25 /// - False positives in some situations when using generics (#3410)
40 /// fn new() -> Self {
47 "Unnecessary structure name repetition whereas `Self` is applicable"
50 declare_lint_pass!(UseSelf => [USE_SELF]);
52 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
54 fn span_use_self_lint(cx: &LateContext<'_, '_>, path: &Path, last_segment: Option<&PathSegment>) {
55 let last_segment = last_segment.unwrap_or_else(|| path.segments.last().expect(SEGMENTS_MSG));
57 // Path segments only include actual path, no methods or fields.
58 let last_path_span = last_segment.ident.span;
59 // Only take path up to the end of last_path_span.
60 let span = path.span.with_hi(last_path_span.hi());
66 "unnecessary structure name repetition",
67 "use the applicable keyword",
69 Applicability::MachineApplicable,
73 struct TraitImplTyVisitor<'a, 'tcx> {
75 cx: &'a LateContext<'a, 'tcx>,
76 trait_type_walker: ty::walk::TypeWalker<'tcx>,
77 impl_type_walker: ty::walk::TypeWalker<'tcx>,
80 impl<'a, 'tcx> Visitor<'tcx> for TraitImplTyVisitor<'a, 'tcx> {
81 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
82 let trait_ty = self.trait_type_walker.next();
83 let impl_ty = self.impl_type_walker.next();
86 if let TyKind::Path(QPath::Resolved(_, path)) = &t.kind;
88 // The implementation and trait types don't match which means that
89 // the concrete type was specified by the implementation
90 if impl_ty != trait_ty;
91 if let Some(impl_ty) = impl_ty;
92 if self.item_type == impl_ty;
95 def::Res::SelfTy(..) => {},
96 _ => span_use_self_lint(self.cx, path, None)
104 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
105 NestedVisitorMap::None
109 fn check_trait_method_impl_decl<'a, 'tcx>(
110 cx: &'a LateContext<'a, 'tcx>,
112 impl_item: &ImplItem,
113 impl_decl: &'tcx FnDecl,
114 impl_trait_ref: &ty::TraitRef<'_>,
116 let trait_method = cx
118 .associated_items(impl_trait_ref.def_id)
120 assoc_item.kind == ty::AssocKind::Method
123 .hygienic_eq(impl_item.ident, assoc_item.ident, impl_trait_ref.def_id)
125 .expect("impl method matches a trait method");
127 let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
128 let trait_method_sig = cx.tcx.erase_late_bound_regions(&trait_method_sig);
130 let impl_method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
131 let impl_method_sig = cx.tcx.fn_sig(impl_method_def_id);
132 let impl_method_sig = cx.tcx.erase_late_bound_regions(&impl_method_sig);
134 let output_ty = if let FunctionRetTy::Return(ty) = &impl_decl.output {
140 // `impl_decl_ty` (of type `hir::Ty`) represents the type declared in the signature.
141 // `impl_ty` (of type `ty:TyS`) is the concrete type that the compiler has determined for
142 // that declaration. We use `impl_decl_ty` to see if the type was declared as `Self`
143 // and use `impl_ty` to check its concrete type.
144 for (impl_decl_ty, (impl_ty, trait_ty)) in impl_decl.inputs.iter().chain(output_ty).zip(
148 .zip(trait_method_sig.inputs_and_output),
150 let mut visitor = TraitImplTyVisitor {
153 trait_type_walker: trait_ty.walk(),
154 impl_type_walker: impl_ty.walk(),
157 visitor.visit_ty(&impl_decl_ty);
161 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UseSelf {
162 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
163 if in_external_macro(cx.sess(), item.span) {
167 if let ItemKind::Impl(.., ref item_type, ref refs) = item.kind;
168 if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.kind;
170 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
171 let should_check = if let Some(ref params) = *parameters {
172 !params.parenthesized && !params.args.iter().any(|arg| match arg {
173 GenericArg::Lifetime(_) => true,
181 let visitor = &mut UseSelfVisitor {
185 let impl_def_id = cx.tcx.hir().local_def_id(item.hir_id);
186 let impl_trait_ref = cx.tcx.impl_trait_ref(impl_def_id);
188 if let Some(impl_trait_ref) = impl_trait_ref {
189 for impl_item_ref in refs {
190 let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
191 if let ImplItemKind::Method(MethodSig{ decl: impl_decl, .. }, impl_body_id)
193 let item_type = cx.tcx.type_of(impl_def_id);
194 check_trait_method_impl_decl(cx, item_type, impl_item, impl_decl, &impl_trait_ref);
196 let body = cx.tcx.hir().body(*impl_body_id);
197 visitor.visit_body(body);
199 visitor.visit_impl_item(impl_item);
203 for impl_item_ref in refs {
204 let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
205 visitor.visit_impl_item(impl_item);
214 struct UseSelfVisitor<'a, 'tcx> {
216 cx: &'a LateContext<'a, 'tcx>,
219 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
220 fn visit_path(&mut self, path: &'tcx Path, _id: HirId) {
221 if path.segments.len() >= 2 {
222 let last_but_one = &path.segments[path.segments.len() - 2];
223 if last_but_one.ident.name != kw::SelfUpper {
224 let enum_def_id = match path.res {
225 Res::Def(DefKind::Variant, variant_def_id) => self.cx.tcx.parent(variant_def_id),
226 Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), ctor_def_id) => {
227 let variant_def_id = self.cx.tcx.parent(ctor_def_id);
228 variant_def_id.and_then(|def_id| self.cx.tcx.parent(def_id))
233 if self.item_path.res.opt_def_id() == enum_def_id {
234 span_use_self_lint(self.cx, path, Some(last_but_one));
239 if path.segments.last().expect(SEGMENTS_MSG).ident.name != kw::SelfUpper {
240 if self.item_path.res == path.res {
241 span_use_self_lint(self.cx, path, None);
242 } else if let Res::Def(DefKind::Ctor(def::CtorOf::Struct, _), ctor_def_id) = path.res {
243 if self.item_path.res.opt_def_id() == self.cx.tcx.parent(ctor_def_id) {
244 span_use_self_lint(self.cx, path, None);
249 walk_path(self, path);
252 fn visit_item(&mut self, item: &'tcx Item) {
255 | ItemKind::Static(..)
257 | ItemKind::Struct(..)
258 | ItemKind::Union(..)
260 | ItemKind::Fn(..) => {
261 // Don't check statements that shadow `Self` or where `Self` can't be used
263 _ => walk_item(self, item),
267 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
268 NestedVisitorMap::All(&self.cx.tcx.hir())