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