]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/single_component_path_imports.rs
Auto merge of #4809 - iankronquist:patch-1, r=flip1995
[rust.git] / clippy_lints / src / single_component_path_imports.rs
1 use crate::utils::span_lint_and_sugg;
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_lint::{EarlyContext, EarlyLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6 use rustc_span::edition::Edition;
7 use syntax::ast::{Item, ItemKind, UseTreeKind};
8
9 declare_clippy_lint! {
10     /// **What it does:** Checking for imports with single component use path.
11     ///
12     /// **Why is this bad?** Import with single component use path such as `use cratename;`
13     /// is not necessary, and thus should be removed.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     ///
19     /// ```rust, ignore
20     /// use regex;
21     ///
22     /// fn main() {
23     ///     regex::Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
24     /// }
25     /// ```
26     /// Better as
27     /// ```rust, ignore
28     /// fn main() {
29     ///     regex::Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
30     /// }
31     /// ```
32     pub SINGLE_COMPONENT_PATH_IMPORTS,
33     style,
34     "imports with single component path are redundant"
35 }
36
37 declare_lint_pass!(SingleComponentPathImports => [SINGLE_COMPONENT_PATH_IMPORTS]);
38
39 impl EarlyLintPass for SingleComponentPathImports {
40     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
41         if_chain! {
42             if cx.sess.opts.edition == Edition::Edition2018;
43             if !item.vis.node.is_pub();
44             if let ItemKind::Use(use_tree) = &item.kind;
45             if let segments = &use_tree.prefix.segments;
46             if segments.len() == 1;
47             if let UseTreeKind::Simple(None, _, _) = use_tree.kind;
48             then {
49                 span_lint_and_sugg(
50                     cx,
51                     SINGLE_COMPONENT_PATH_IMPORTS,
52                     item.span,
53                     "this import is redundant",
54                     "remove it entirely",
55                     String::new(),
56                     Applicability::MachineApplicable
57                 );
58             }
59         }
60     }
61 }