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