]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/wildcard_imports.rs
Rollup merge of #72033 - XAMPPRocky:relnotes-1.44.0, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / wildcard_imports.rs
1 use crate::utils::{in_macro, snippet, snippet_with_applicability, span_lint_and_sugg};
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::{
5     def::{DefKind, Res},
6     Item, ItemKind, PathSegment, UseKind,
7 };
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 use rustc_span::BytePos;
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for `use Enum::*`.
14     ///
15     /// **Why is this bad?** It is usually better style to use the prefixed name of
16     /// an enumeration variant, rather than importing variants.
17     ///
18     /// **Known problems:** Old-style enumerations that prefix the variants are
19     /// still around.
20     ///
21     /// **Example:**
22     /// ```rust
23     /// use std::cmp::Ordering::*;
24     /// ```
25     pub ENUM_GLOB_USE,
26     pedantic,
27     "use items that import all variants of an enum"
28 }
29
30 declare_clippy_lint! {
31     /// **What it does:** Checks for wildcard imports `use _::*`.
32     ///
33     /// **Why is this bad?** wildcard imports can polute the namespace. This is especially bad if
34     /// you try to import something through a wildcard, that already has been imported by name from
35     /// a different source:
36     ///
37     /// ```rust,ignore
38     /// use crate1::foo; // Imports a function named foo
39     /// use crate2::*; // Has a function named foo
40     ///
41     /// foo(); // Calls crate1::foo
42     /// ```
43     ///
44     /// This can lead to confusing error messages at best and to unexpected behavior at worst.
45     ///
46     /// **Exceptions:**
47     ///
48     /// Wildcard imports are allowed from modules named `prelude`. Many crates (including the standard library)
49     /// provide modules named "prelude" specifically designed for wildcard import.
50     ///
51     /// `use super::*` is allowed in test modules. This is defined as any module with "test" in the name.
52     ///
53     /// These exceptions can be disabled using the `warn-on-all-wildcard-imports` configuration flag.
54     ///
55     /// **Known problems:** If macros are imported through the wildcard, this macro is not included
56     /// by the suggestion and has to be added by hand.
57     ///
58     /// Applying the suggestion when explicit imports of the things imported with a glob import
59     /// exist, may result in `unused_imports` warnings.
60     ///
61     /// **Example:**
62     ///
63     /// Bad:
64     /// ```rust,ignore
65     /// use crate1::*;
66     ///
67     /// foo();
68     /// ```
69     ///
70     /// Good:
71     /// ```rust,ignore
72     /// use crate1::foo;
73     ///
74     /// foo();
75     /// ```
76     pub WILDCARD_IMPORTS,
77     pedantic,
78     "lint `use _::*` statements"
79 }
80
81 #[derive(Default)]
82 pub struct WildcardImports {
83     warn_on_all: bool,
84     test_modules_deep: u32,
85 }
86
87 impl WildcardImports {
88     pub fn new(warn_on_all: bool) -> Self {
89         Self {
90             warn_on_all,
91             test_modules_deep: 0,
92         }
93     }
94 }
95
96 impl_lint_pass!(WildcardImports => [ENUM_GLOB_USE, WILDCARD_IMPORTS]);
97
98 impl LateLintPass<'_, '_> for WildcardImports {
99     fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &Item<'_>) {
100         if is_test_module_or_function(item) {
101             self.test_modules_deep = self.test_modules_deep.saturating_add(1);
102         }
103         if item.vis.node.is_pub() || item.vis.node.is_pub_restricted() {
104             return;
105         }
106         if_chain! {
107             if let ItemKind::Use(use_path, UseKind::Glob) = &item.kind;
108             if self.warn_on_all || !self.check_exceptions(item, use_path.segments);
109             let used_imports = cx.tcx.names_imported_by_glob_use(item.hir_id.owner);
110             if !used_imports.is_empty(); // Already handled by `unused_imports`
111             then {
112                 let mut applicability = Applicability::MachineApplicable;
113                 let import_source_snippet = snippet_with_applicability(cx, use_path.span, "..", &mut applicability);
114                 let (span, braced_glob) = if import_source_snippet.is_empty() {
115                     // This is a `_::{_, *}` import
116                     // In this case `use_path.span` is empty and ends directly in front of the `*`,
117                     // so we need to extend it by one byte.
118                     (
119                         use_path.span.with_hi(use_path.span.hi() + BytePos(1)),
120                         true,
121                     )
122                 } else {
123                     // In this case, the `use_path.span` ends right before the `::*`, so we need to
124                     // extend it up to the `*`. Since it is hard to find the `*` in weird
125                     // formattings like `use _ ::  *;`, we extend it up to, but not including the
126                     // `;`. In nested imports, like `use _::{inner::*, _}` there is no `;` and we
127                     // can just use the end of the item span
128                     let mut span = use_path.span.with_hi(item.span.hi());
129                     if snippet(cx, span, "").ends_with(';') {
130                         span = use_path.span.with_hi(item.span.hi() - BytePos(1));
131                     }
132                     (
133                         span, false,
134                     )
135                 };
136
137                 let imports_string = if used_imports.len() == 1 {
138                     used_imports.iter().next().unwrap().to_string()
139                 } else {
140                     let mut imports = used_imports
141                         .iter()
142                         .map(ToString::to_string)
143                         .collect::<Vec<_>>();
144                     imports.sort();
145                     if braced_glob {
146                         imports.join(", ")
147                     } else {
148                         format!("{{{}}}", imports.join(", "))
149                     }
150                 };
151
152                 let sugg = if braced_glob {
153                     imports_string
154                 } else {
155                     format!("{}::{}", import_source_snippet, imports_string)
156                 };
157
158                 let (lint, message) = if let Res::Def(DefKind::Enum, _) = use_path.res {
159                     (ENUM_GLOB_USE, "usage of wildcard import for enum variants")
160                 } else {
161                     (WILDCARD_IMPORTS, "usage of wildcard import")
162                 };
163
164                 span_lint_and_sugg(
165                     cx,
166                     lint,
167                     span,
168                     message,
169                     "try",
170                     sugg,
171                     applicability,
172                 );
173             }
174         }
175     }
176
177     fn check_item_post(&mut self, _: &LateContext<'_, '_>, item: &Item<'_>) {
178         if is_test_module_or_function(item) {
179             self.test_modules_deep = self.test_modules_deep.saturating_sub(1);
180         }
181     }
182 }
183
184 impl WildcardImports {
185     fn check_exceptions(&self, item: &Item<'_>, segments: &[PathSegment<'_>]) -> bool {
186         in_macro(item.span)
187             || is_prelude_import(segments)
188             || (is_super_only_import(segments) && self.test_modules_deep > 0)
189     }
190 }
191
192 // Allow "...prelude::*" imports.
193 // Many crates have a prelude, and it is imported as a glob by design.
194 fn is_prelude_import(segments: &[PathSegment<'_>]) -> bool {
195     segments
196         .iter()
197         .last()
198         .map_or(false, |ps| ps.ident.as_str() == "prelude")
199 }
200
201 // Allow "super::*" imports in tests.
202 fn is_super_only_import(segments: &[PathSegment<'_>]) -> bool {
203     segments.len() == 1 && segments[0].ident.as_str() == "super"
204 }
205
206 fn is_test_module_or_function(item: &Item<'_>) -> bool {
207     matches!(item.kind, ItemKind::Mod(..)) && item.ident.name.as_str().contains("test")
208 }