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