1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::{declare_lint, lint_array};
4 use rustc::hir::intravisit::{walk_path, NestedVisitorMap, Visitor};
5 use crate::utils::{in_macro, span_lint_and_then};
6 use syntax::ast::NodeId;
7 use syntax_pos::symbol::keywords::SelfType;
9 /// **What it does:** Checks for unnecessary repetition of structure name when a
10 /// replacement with `Self` is applicable.
12 /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
14 /// feels inconsistent.
16 /// **Known problems:** None.
31 /// fn new() -> Self {
36 declare_clippy_lint! {
39 "Unnecessary structure name repetition whereas `Self` is applicable"
42 #[derive(Copy, Clone, Default)]
45 impl LintPass for UseSelf {
46 fn get_lints(&self) -> LintArray {
51 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
53 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UseSelf {
54 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
55 if in_macro(item.span) {
59 if let ItemKind::Impl(.., ref item_type, ref refs) = item.node;
60 if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.node;
62 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
63 let should_check = if let Some(ref params) = *parameters {
64 !params.parenthesized && !params.args.iter().any(|arg| match arg {
65 GenericArg::Lifetime(_) => true,
66 GenericArg::Type(_) => false,
72 let visitor = &mut UseSelfVisitor {
76 for impl_item_ref in refs {
77 visitor.visit_impl_item(cx.tcx.hir.impl_item(impl_item_ref.id));
85 struct UseSelfVisitor<'a, 'tcx: 'a> {
87 cx: &'a LateContext<'a, 'tcx>,
90 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
91 fn visit_path(&mut self, path: &'tcx Path, _id: NodeId) {
92 if self.item_path.def == path.def && path.segments.last().expect(SEGMENTS_MSG).ident.name != SelfType.name() {
93 span_lint_and_then(self.cx, USE_SELF, path.span, "unnecessary structure name repetition", |db| {
94 db.span_suggestion(path.span, "use the applicable keyword", "Self".to_owned());
98 walk_path(self, path);
101 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
102 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir)