Auto merge of #11979 - J-ZhengLi:issue11428, r=Alexendoo

add configuration for [`wildcard_imports`] to ignore certain imports

fixes: #11428

changelog: add configuration `ignored-wildcard-imports` for lint [`wildcard_imports`]
This commit is contained in:
bors 2024-02-02 21:28:49 +00:00
commit c82162eb71
14 changed files with 184 additions and 7 deletions

View File

@ -5824,4 +5824,5 @@ Released 2018-09-13
[`check-private-items`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-private-items [`check-private-items`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-private-items
[`pub-underscore-fields-behavior`]: https://doc.rust-lang.org/clippy/lint_configuration.html#pub-underscore-fields-behavior [`pub-underscore-fields-behavior`]: https://doc.rust-lang.org/clippy/lint_configuration.html#pub-underscore-fields-behavior
[`allow-comparison-to-zero`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allow-comparison-to-zero [`allow-comparison-to-zero`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allow-comparison-to-zero
[`allowed-wildcard-imports`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allowed-wildcard-imports
<!-- end autogenerated links to configuration documentation --> <!-- end autogenerated links to configuration documentation -->

View File

@ -838,3 +838,25 @@ Don't lint when comparing the result of a modulo operation to zero.
* [`modulo_arithmetic`](https://rust-lang.github.io/rust-clippy/master/index.html#modulo_arithmetic) * [`modulo_arithmetic`](https://rust-lang.github.io/rust-clippy/master/index.html#modulo_arithmetic)
## `allowed-wildcard-imports`
List of path segments allowed to have wildcard imports.
#### Example
```toml
allowed-wildcard-imports = [ "utils", "common" ]
```
#### Noteworthy
1. This configuration has no effects if used with `warn_on_all_wildcard_imports = true`.
2. Paths with any segment that containing the word 'prelude'
are already allowed by default.
**Default Value:** `[]`
---
**Affected lints:**
* [`wildcard_imports`](https://rust-lang.github.io/rust-clippy/master/index.html#wildcard_imports)

View File

@ -571,6 +571,22 @@ pub fn get_configuration_metadata() -> Vec<ClippyConfiguration> {
/// ///
/// Don't lint when comparing the result of a modulo operation to zero. /// Don't lint when comparing the result of a modulo operation to zero.
(allow_comparison_to_zero: bool = true), (allow_comparison_to_zero: bool = true),
/// Lint: WILDCARD_IMPORTS.
///
/// List of path segments allowed to have wildcard imports.
///
/// #### Example
///
/// ```toml
/// allowed-wildcard-imports = [ "utils", "common" ]
/// ```
///
/// #### Noteworthy
///
/// 1. This configuration has no effects if used with `warn_on_all_wildcard_imports = true`.
/// 2. Paths with any segment that containing the word 'prelude'
/// are already allowed by default.
(allowed_wildcard_imports: FxHashSet<String> = FxHashSet::default()),
} }
/// Search for the configuration file. /// Search for the configuration file.

View File

@ -524,6 +524,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
ref allowed_dotfiles, ref allowed_dotfiles,
ref allowed_idents_below_min_chars, ref allowed_idents_below_min_chars,
ref allowed_scripts, ref allowed_scripts,
ref allowed_wildcard_imports,
ref arithmetic_side_effects_allowed_binary, ref arithmetic_side_effects_allowed_binary,
ref arithmetic_side_effects_allowed_unary, ref arithmetic_side_effects_allowed_unary,
ref arithmetic_side_effects_allowed, ref arithmetic_side_effects_allowed,
@ -876,7 +877,12 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
)) ))
}); });
store.register_early_pass(|| Box::new(option_env_unwrap::OptionEnvUnwrap)); store.register_early_pass(|| Box::new(option_env_unwrap::OptionEnvUnwrap));
store.register_late_pass(move |_| Box::new(wildcard_imports::WildcardImports::new(warn_on_all_wildcard_imports))); store.register_late_pass(move |_| {
Box::new(wildcard_imports::WildcardImports::new(
warn_on_all_wildcard_imports,
allowed_wildcard_imports.clone(),
))
});
store.register_late_pass(|_| Box::<redundant_pub_crate::RedundantPubCrate>::default()); store.register_late_pass(|_| Box::<redundant_pub_crate::RedundantPubCrate>::default());
store.register_late_pass(|_| Box::new(unnamed_address::UnnamedAddress)); store.register_late_pass(|_| Box::new(unnamed_address::UnnamedAddress));
store.register_late_pass(|_| Box::<dereference::Dereferencing<'_>>::default()); store.register_late_pass(|_| Box::<dereference::Dereferencing<'_>>::default());

View File

@ -1,6 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_test_module_or_function; use clippy_utils::is_test_module_or_function;
use clippy_utils::source::{snippet, snippet_with_applicability}; use clippy_utils::source::{snippet, snippet_with_applicability};
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_hir::{Item, ItemKind, PathSegment, UseKind}; use rustc_hir::{Item, ItemKind, PathSegment, UseKind};
@ -100,13 +101,15 @@
pub struct WildcardImports { pub struct WildcardImports {
warn_on_all: bool, warn_on_all: bool,
test_modules_deep: u32, test_modules_deep: u32,
allowed_segments: FxHashSet<String>,
} }
impl WildcardImports { impl WildcardImports {
pub fn new(warn_on_all: bool) -> Self { pub fn new(warn_on_all: bool, allowed_wildcard_imports: FxHashSet<String>) -> Self {
Self { Self {
warn_on_all, warn_on_all,
test_modules_deep: 0, test_modules_deep: 0,
allowed_segments: allowed_wildcard_imports,
} }
} }
} }
@ -190,6 +193,7 @@ fn check_exceptions(&self, item: &Item<'_>, segments: &[PathSegment<'_>]) -> boo
item.span.from_expansion() item.span.from_expansion()
|| is_prelude_import(segments) || is_prelude_import(segments)
|| (is_super_only_import(segments) && self.test_modules_deep > 0) || (is_super_only_import(segments) && self.test_modules_deep > 0)
|| is_allowed_via_config(segments, &self.allowed_segments)
} }
} }
@ -198,10 +202,18 @@ fn check_exceptions(&self, item: &Item<'_>, segments: &[PathSegment<'_>]) -> boo
fn is_prelude_import(segments: &[PathSegment<'_>]) -> bool { fn is_prelude_import(segments: &[PathSegment<'_>]) -> bool {
segments segments
.iter() .iter()
.any(|ps| ps.ident.name.as_str().contains(sym::prelude.as_str())) .any(|ps| ps.ident.as_str().contains(sym::prelude.as_str()))
} }
// Allow "super::*" imports in tests. // Allow "super::*" imports in tests.
fn is_super_only_import(segments: &[PathSegment<'_>]) -> bool { fn is_super_only_import(segments: &[PathSegment<'_>]) -> bool {
segments.len() == 1 && segments[0].ident.name == kw::Super segments.len() == 1 && segments[0].ident.name == kw::Super
} }
// Allow skipping imports containing user configured segments,
// i.e. "...::utils::...::*" if user put `allowed-wildcard-imports = ["utils"]` in `Clippy.toml`
fn is_allowed_via_config(segments: &[PathSegment<'_>], allowed_segments: &FxHashSet<String>) -> bool {
// segment matching need to be exact instead of using 'contains', in case user unintentionaly put
// a single character in the config thus skipping most of the warnings.
segments.iter().any(|seg| allowed_segments.contains(seg.ident.as_str()))
}

View File

@ -15,6 +15,7 @@ error: error reading Clippy's configuration file: unknown field `foobar`, expect
allowed-duplicate-crates allowed-duplicate-crates
allowed-idents-below-min-chars allowed-idents-below-min-chars
allowed-scripts allowed-scripts
allowed-wildcard-imports
arithmetic-side-effects-allowed arithmetic-side-effects-allowed
arithmetic-side-effects-allowed-binary arithmetic-side-effects-allowed-binary
arithmetic-side-effects-allowed-unary arithmetic-side-effects-allowed-unary
@ -93,6 +94,7 @@ error: error reading Clippy's configuration file: unknown field `barfoo`, expect
allowed-duplicate-crates allowed-duplicate-crates
allowed-idents-below-min-chars allowed-idents-below-min-chars
allowed-scripts allowed-scripts
allowed-wildcard-imports
arithmetic-side-effects-allowed arithmetic-side-effects-allowed
arithmetic-side-effects-allowed-binary arithmetic-side-effects-allowed-binary
arithmetic-side-effects-allowed-unary arithmetic-side-effects-allowed-unary
@ -171,6 +173,7 @@ error: error reading Clippy's configuration file: unknown field `allow_mixed_uni
allowed-duplicate-crates allowed-duplicate-crates
allowed-idents-below-min-chars allowed-idents-below-min-chars
allowed-scripts allowed-scripts
allowed-wildcard-imports
arithmetic-side-effects-allowed arithmetic-side-effects-allowed
arithmetic-side-effects-allowed-binary arithmetic-side-effects-allowed-binary
arithmetic-side-effects-allowed-unary arithmetic-side-effects-allowed-unary

View File

@ -1 +1,4 @@
warn-on-all-wildcard-imports = true warn-on-all-wildcard-imports = true
# This should be ignored since `warn-on-all-wildcard-imports` has higher precedence
allowed-wildcard-imports = ["utils"]

View File

@ -3,9 +3,28 @@
mod prelude { mod prelude {
pub const FOO: u8 = 1; pub const FOO: u8 = 1;
} }
mod utils {
pub const BAR: u8 = 1;
pub fn print() {}
}
mod my_crate {
pub mod utils {
pub fn my_util_fn() {}
}
}
use utils::{BAR, print};
//~^ ERROR: usage of wildcard import
use my_crate::utils::my_util_fn;
//~^ ERROR: usage of wildcard import
use prelude::FOO; use prelude::FOO;
//~^ ERROR: usage of wildcard import //~^ ERROR: usage of wildcard import
fn main() { fn main() {
let _ = FOO; let _ = FOO;
let _ = BAR;
print();
my_util_fn();
} }

View File

@ -3,9 +3,28 @@
mod prelude { mod prelude {
pub const FOO: u8 = 1; pub const FOO: u8 = 1;
} }
mod utils {
pub const BAR: u8 = 1;
pub fn print() {}
}
mod my_crate {
pub mod utils {
pub fn my_util_fn() {}
}
}
use utils::*;
//~^ ERROR: usage of wildcard import
use my_crate::utils::*;
//~^ ERROR: usage of wildcard import
use prelude::*; use prelude::*;
//~^ ERROR: usage of wildcard import //~^ ERROR: usage of wildcard import
fn main() { fn main() {
let _ = FOO; let _ = FOO;
let _ = BAR;
print();
my_util_fn();
} }

View File

@ -1,11 +1,23 @@
error: usage of wildcard import error: usage of wildcard import
--> $DIR/wildcard_imports.rs:6:5 --> $DIR/wildcard_imports.rs:18:5
| |
LL | use prelude::*; LL | use utils::*;
| ^^^^^^^^^^ help: try: `prelude::FOO` | ^^^^^^^^ help: try: `utils::{BAR, print}`
| |
= note: `-D clippy::wildcard-imports` implied by `-D warnings` = note: `-D clippy::wildcard-imports` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::wildcard_imports)]` = help: to override `-D warnings` add `#[allow(clippy::wildcard_imports)]`
error: aborting due to 1 previous error error: usage of wildcard import
--> $DIR/wildcard_imports.rs:20:5
|
LL | use my_crate::utils::*;
| ^^^^^^^^^^^^^^^^^^ help: try: `my_crate::utils::my_util_fn`
error: usage of wildcard import
--> $DIR/wildcard_imports.rs:22:5
|
LL | use prelude::*;
| ^^^^^^^^^^ help: try: `prelude::FOO`
error: aborting due to 3 previous errors

View File

@ -0,0 +1 @@
allowed-wildcard-imports = ["utils"]

View File

@ -0,0 +1,26 @@
#![warn(clippy::wildcard_imports)]
mod utils {
pub fn print() {}
}
mod utils_plus {
pub fn do_something() {}
}
mod my_crate {
pub mod utils {
pub fn my_util_fn() {}
}
}
use my_crate::utils::*;
use utils::*;
use utils_plus::do_something;
//~^ ERROR: usage of wildcard import
fn main() {
print();
my_util_fn();
do_something();
}

View File

@ -0,0 +1,26 @@
#![warn(clippy::wildcard_imports)]
mod utils {
pub fn print() {}
}
mod utils_plus {
pub fn do_something() {}
}
mod my_crate {
pub mod utils {
pub fn my_util_fn() {}
}
}
use my_crate::utils::*;
use utils::*;
use utils_plus::*;
//~^ ERROR: usage of wildcard import
fn main() {
print();
my_util_fn();
do_something();
}

View File

@ -0,0 +1,11 @@
error: usage of wildcard import
--> $DIR/wildcard_imports.rs:19:5
|
LL | use utils_plus::*;
| ^^^^^^^^^^^^^ help: try: `utils_plus::do_something`
|
= note: `-D clippy::wildcard-imports` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::wildcard_imports)]`
error: aborting due to 1 previous error