Skip to content

Commit 46659ac

Browse files
committed
add configuration to allow skipping on some certain traits & collect metadata
1 parent 40ec760 commit 46659ac

File tree

12 files changed

+159
-52
lines changed

12 files changed

+159
-52
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5942,6 +5942,7 @@ Released 2018-09-13
59425942
[`allow-one-hash-in-raw-strings`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allow-one-hash-in-raw-strings
59435943
[`allow-print-in-tests`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allow-print-in-tests
59445944
[`allow-private-module-inception`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allow-private-module-inception
5945+
[`allow-renamed-params-for`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allow-renamed-params-for
59455946
[`allow-unwrap-in-tests`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allow-unwrap-in-tests
59465947
[`allow-useless-vec-in-tests`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allow-useless-vec-in-tests
59475948
[`allowed-dotfiles`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allowed-dotfiles

book/src/lint_configuration.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,28 @@ Whether to allow module inception if it's not public.
122122
* [`module_inception`](https://rust-lang.github.io/rust-clippy/master/index.html#module_inception)
123123

124124

125+
## `allow-renamed-params-for`
126+
List of trait paths to ignore when checking renamed function parameters.
127+
128+
#### Example
129+
130+
```toml
131+
allow-renamed-params-for = [ "std::convert::From" ]
132+
```
133+
134+
#### Noteworthy
135+
136+
- By default, the following traits are ignored: `From`, `TryFrom`, `FromStr`
137+
- `".."` can be used as part of the list to indicate that the configured values should be appended to the
138+
default configuration of Clippy. By default, any configuration will replace the default value.
139+
140+
**Default Value:** `["core::convert::From", "core::convert::TryFrom", "core::str::FromStr"]`
141+
142+
---
143+
**Affected lints:**
144+
* [`renamed_function_params`](https://rust-lang.github.io/rust-clippy/master/index.html#renamed_function_params)
145+
146+
125147
## `allow-unwrap-in-tests`
126148
Whether `unwrap` should be allowed in test functions or `#[cfg(test)]`
127149

clippy_config/src/conf.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ const DEFAULT_DOC_VALID_IDENTS: &[&str] = &[
4040
const DEFAULT_DISALLOWED_NAMES: &[&str] = &["foo", "baz", "quux"];
4141
const DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS: &[&str] = &["i", "j", "x", "y", "z", "w", "n"];
4242
const DEFAULT_ALLOWED_PREFIXES: &[&str] = &["to", "as", "into", "from", "try_into", "try_from"];
43+
const DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS: &[&str] =
44+
&["core::convert::From", "core::convert::TryFrom", "core::str::FromStr"];
4345

4446
/// Conf with parse errors
4547
#[derive(Default)]
@@ -613,6 +615,23 @@ define_Conf! {
613615
/// - Use `".."` as part of the list to indicate that the configured values should be appended to the
614616
/// default configuration of Clippy. By default, any configuration will replace the default value
615617
(allowed_prefixes: Vec<String> = DEFAULT_ALLOWED_PREFIXES.iter().map(ToString::to_string).collect()),
618+
/// Lint: RENAMED_FUNCTION_PARAMS.
619+
///
620+
/// List of trait paths to ignore when checking renamed function parameters.
621+
///
622+
/// #### Example
623+
///
624+
/// ```toml
625+
/// allow-renamed-params-for = [ "std::convert::From" ]
626+
/// ```
627+
///
628+
/// #### Noteworthy
629+
///
630+
/// - By default, the following traits are ignored: `From`, `TryFrom`, `FromStr`
631+
/// - `".."` can be used as part of the list to indicate that the configured values should be appended to the
632+
/// default configuration of Clippy. By default, any configuration will replace the default value.
633+
(allow_renamed_params_for: Vec<String> =
634+
DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS.iter().map(ToString::to_string).collect()),
616635
}
617636

618637
/// Search for the configuration file.
@@ -674,6 +693,10 @@ fn deserialize(file: &SourceFile) -> TryConf {
674693
extend_vec_if_indicator_present(&mut conf.conf.doc_valid_idents, DEFAULT_DOC_VALID_IDENTS);
675694
extend_vec_if_indicator_present(&mut conf.conf.disallowed_names, DEFAULT_DISALLOWED_NAMES);
676695
extend_vec_if_indicator_present(&mut conf.conf.allowed_prefixes, DEFAULT_ALLOWED_PREFIXES);
696+
extend_vec_if_indicator_present(
697+
&mut conf.conf.allow_renamed_params_for,
698+
DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS,
699+
);
677700
// TODO: THIS SHOULD BE TESTED, this comment will be gone soon
678701
if conf.conf.allowed_idents_below_min_chars.contains("..") {
679702
conf.conf

clippy_lints/src/functions/mod.rs

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@ mod result;
77
mod too_many_arguments;
88
mod too_many_lines;
99

10+
use clippy_utils::def_path_def_ids;
1011
use rustc_hir as hir;
1112
use rustc_hir::intravisit;
1213
use rustc_lint::{LateContext, LateLintPass};
1314
use rustc_session::impl_lint_pass;
14-
use rustc_span::def_id::LocalDefId;
15+
use rustc_span::def_id::{DefIdSet, LocalDefId};
1516
use rustc_span::Span;
1617

1718
declare_clippy_lint! {
@@ -373,19 +374,19 @@ declare_clippy_lint! {
373374
/// ```rust
374375
/// struct A(u32);
375376
///
376-
/// impl From<A> for String {
377-
/// fn from(a: A) -> Self {
378-
/// a.0.to_string()
377+
/// impl PartialEq for A {
378+
/// fn eq(&self, b: &Self) -> bool {
379+
/// self.0 == b.0
379380
/// }
380381
/// }
381382
/// ```
382383
/// Use instead:
383384
/// ```rust
384385
/// struct A(u32);
385386
///
386-
/// impl From<A> for String {
387-
/// fn from(value: A) -> Self {
388-
/// value.0.to_string()
387+
/// impl PartialEq for A {
388+
/// fn eq(&self, other: &Self) -> bool {
389+
/// self.0 == other.0
389390
/// }
390391
/// }
391392
/// ```
@@ -395,13 +396,16 @@ declare_clippy_lint! {
395396
"renamed function parameters in trait implementation"
396397
}
397398

398-
#[derive(Copy, Clone)]
399-
#[allow(clippy::struct_field_names)]
399+
#[derive(Clone)]
400400
pub struct Functions {
401401
too_many_arguments_threshold: u64,
402402
too_many_lines_threshold: u64,
403403
large_error_threshold: u64,
404404
avoid_breaking_exported_api: bool,
405+
allow_renamed_params_for: Vec<String>,
406+
/// A set of resolved `def_id` of traits that are configured to allow
407+
/// function params renaming.
408+
trait_ids: DefIdSet,
405409
}
406410

407411
impl Functions {
@@ -410,12 +414,15 @@ impl Functions {
410414
too_many_lines_threshold: u64,
411415
large_error_threshold: u64,
412416
avoid_breaking_exported_api: bool,
417+
allow_renamed_params_for: Vec<String>,
413418
) -> Self {
414419
Self {
415420
too_many_arguments_threshold,
416421
too_many_lines_threshold,
417422
large_error_threshold,
418423
avoid_breaking_exported_api,
424+
allow_renamed_params_for,
425+
trait_ids: DefIdSet::default(),
419426
}
420427
}
421428
}
@@ -461,7 +468,7 @@ impl<'tcx> LateLintPass<'tcx> for Functions {
461468
must_use::check_impl_item(cx, item);
462469
result::check_impl_item(cx, item, self.large_error_threshold);
463470
impl_trait_in_params::check_impl_item(cx, item);
464-
renamed_function_params::check_impl_item(cx, item);
471+
renamed_function_params::check_impl_item(cx, item, &self.trait_ids);
465472
}
466473

467474
fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
@@ -471,4 +478,12 @@ impl<'tcx> LateLintPass<'tcx> for Functions {
471478
result::check_trait_item(cx, item, self.large_error_threshold);
472479
impl_trait_in_params::check_trait_item(cx, item, self.avoid_breaking_exported_api);
473480
}
481+
482+
fn check_crate(&mut self, cx: &LateContext<'tcx>) {
483+
for path in &self.allow_renamed_params_for {
484+
let path_segments: Vec<&str> = path.split("::").collect();
485+
let ids = def_path_def_ids(cx, &path_segments);
486+
self.trait_ids.extend(ids);
487+
}
488+
}
474489
}

clippy_lints/src/functions/renamed_function_params.rs

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,26 @@
11
use clippy_utils::diagnostics::span_lint_and_then;
22
use rustc_errors::{Applicability, MultiSpan};
3-
use rustc_hir::def_id::DefId;
3+
use rustc_hir::def_id::{DefId, DefIdSet};
44
use rustc_hir::hir_id::OwnerId;
5-
use rustc_hir::{ImplItem, ImplItemKind, ItemKind, Node};
5+
use rustc_hir::{Impl, ImplItem, ImplItemKind, ImplItemRef, ItemKind, Node, TraitRef};
66
use rustc_lint::LateContext;
77
use rustc_span::symbol::{kw, Ident, Symbol};
88
use rustc_span::Span;
99

1010
use super::RENAMED_FUNCTION_PARAMS;
1111

12-
pub(super) fn check_impl_item(cx: &LateContext<'_>, item: &ImplItem<'_>) {
12+
pub(super) fn check_impl_item(cx: &LateContext<'_>, item: &ImplItem<'_>, ignored_traits: &DefIdSet) {
1313
if !item.span.from_expansion()
1414
&& let ImplItemKind::Fn(_, body_id) = item.kind
15-
&& let Some(did) = trait_item_def_id_of_impl(cx, item.owner_id)
15+
&& let parent_node = cx.tcx.parent_hir_node(item.hir_id())
16+
&& let Node::Item(parent_item) = parent_node
17+
&& let ItemKind::Impl(Impl {
18+
items,
19+
of_trait: Some(trait_ref),
20+
..
21+
}) = &parent_item.kind
22+
&& let Some(did) = trait_item_def_id_of_impl(items, item.owner_id)
23+
&& !is_from_ignored_trait(trait_ref, ignored_traits)
1624
{
1725
let mut param_idents_iter = cx.tcx.hir().body_param_names(body_id);
1826
let mut default_param_idents_iter = cx.tcx.fn_arg_names(did).iter().copied();
@@ -25,7 +33,7 @@ pub(super) fn check_impl_item(cx: &LateContext<'_>, item: &ImplItem<'_>) {
2533
cx,
2634
RENAMED_FUNCTION_PARAMS,
2735
multi_span,
28-
&format!("renamed function parameter{plural} of trait impl"),
36+
format!("renamed function parameter{plural} of trait impl"),
2937
|diag| {
3038
diag.multipart_suggestion(
3139
format!("consider using the default name{plural}"),
@@ -83,20 +91,20 @@ fn is_unused_or_empty_symbol(symbol: Symbol) -> bool {
8391
symbol.is_empty() || symbol == kw::Underscore || symbol.as_str().starts_with('_')
8492
}
8593

86-
/// Get the [`trait_item_def_id`](rustc_hir::hir::ImplItemRef::trait_item_def_id) of an impl item.
87-
fn trait_item_def_id_of_impl(cx: &LateContext<'_>, impl_item_id: OwnerId) -> Option<DefId> {
88-
let trait_node = cx.tcx.parent_hir_node(impl_item_id.into());
89-
if let Node::Item(item) = trait_node
90-
&& let ItemKind::Impl(impl_) = &item.kind
91-
{
92-
impl_.items.iter().find_map(|item| {
93-
if item.id.owner_id == impl_item_id {
94-
item.trait_item_def_id
95-
} else {
96-
None
97-
}
98-
})
99-
} else {
100-
None
101-
}
94+
/// Get the [`trait_item_def_id`](ImplItemRef::trait_item_def_id) of a relevant impl item.
95+
fn trait_item_def_id_of_impl(items: &[ImplItemRef], target: OwnerId) -> Option<DefId> {
96+
items.iter().find_map(|item| {
97+
if item.id.owner_id == target {
98+
item.trait_item_def_id
99+
} else {
100+
None
101+
}
102+
})
103+
}
104+
105+
fn is_from_ignored_trait(of_trait: &TraitRef<'_>, ignored_traits: &DefIdSet) -> bool {
106+
let Some(trait_did) = of_trait.trait_def_id() else {
107+
return false;
108+
};
109+
ignored_traits.contains(&trait_did)
102110
}

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
595595
ref allowed_duplicate_crates,
596596
allow_comparison_to_zero,
597597
ref allowed_prefixes,
598+
ref allow_renamed_params_for,
598599

599600
blacklisted_names: _,
600601
cyclomatic_complexity_threshold: _,
@@ -788,6 +789,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
788789
too_many_lines_threshold,
789790
large_error_threshold,
790791
avoid_breaking_exported_api,
792+
allow_renamed_params_for.clone(),
791793
))
792794
});
793795
store.register_late_pass(move |_| Box::new(doc::Documentation::new(doc_valid_idents, check_private_items)));
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Ignore `From`, `TryFrom`, `FromStr` by default
2+
# allow-renamed-params-for = []
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Ignore `From`, `TryFrom`, `FromStr` by default
2+
allow-renamed-params-for = [ "..", "std::ops::Add", "renamed_function_params::MyTrait" ]
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,32 @@
11
error: renamed function parameter of trait impl
2-
--> tests/ui/renamed_function_params.rs:22:13
2+
--> tests/ui-toml/renamed_function_params/renamed_function_params.rs:30:18
33
|
4-
LL | fn from(b: B) -> Self {
5-
| ^ help: consider using the default name: `value`
4+
LL | fn eq(&self, rhs: &Self) -> bool {
5+
| ^^^ help: consider using the default name: `other`
66
|
77
= note: `-D clippy::renamed-function-params` implied by `-D warnings`
88
= help: to override `-D warnings` add `#[allow(clippy::renamed_function_params)]`
99

1010
error: renamed function parameter of trait impl
11-
--> tests/ui/renamed_function_params.rs:28:18
12-
|
13-
LL | fn eq(&self, rhs: &Self) -> bool {
14-
| ^^^ help: consider using the default name: `other`
15-
16-
error: renamed function parameter of trait impl
17-
--> tests/ui/renamed_function_params.rs:32:18
11+
--> tests/ui-toml/renamed_function_params/renamed_function_params.rs:34:18
1812
|
1913
LL | fn ne(&self, rhs: &Self) -> bool {
2014
| ^^^ help: consider using the default name: `other`
2115

2216
error: renamed function parameter of trait impl
23-
--> tests/ui/renamed_function_params.rs:46:19
17+
--> tests/ui-toml/renamed_function_params/renamed_function_params.rs:48:19
2418
|
25-
LL | fn foo(&self, i_dont_wanna_use_your_name: u8) {}
19+
LL | fn foo(&self, i_dont_wanna_use_your_name: u8) {} // only lint in `extend`
2620
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using the default name: `val`
2721

2822
error: renamed function parameter of trait impl
29-
--> tests/ui/renamed_function_params.rs:54:31
23+
--> tests/ui-toml/renamed_function_params/renamed_function_params.rs:55:31
3024
|
3125
LL | fn hash<H: Hasher>(&self, states: &mut H) {
3226
| ^^^^^^ help: consider using the default name: `state`
3327

3428
error: renamed function parameters of trait impl
35-
--> tests/ui/renamed_function_params.rs:58:30
29+
--> tests/ui-toml/renamed_function_params/renamed_function_params.rs:59:30
3630
|
3731
LL | fn hash_slice<H: Hasher>(date: &[Self], states: &mut H) {
3832
| ^^^^ ^^^^^^
@@ -43,10 +37,10 @@ LL | fn hash_slice<H: Hasher>(data: &[Self], state: &mut H) {
4337
| ~~~~ ~~~~~
4438

4539
error: renamed function parameter of trait impl
46-
--> tests/ui/renamed_function_params.rs:79:18
40+
--> tests/ui-toml/renamed_function_params/renamed_function_params.rs:80:18
4741
|
4842
LL | fn add(self, b: B) -> C {
4943
| ^ help: consider using the default name: `rhs`
5044

51-
error: aborting due to 7 previous errors
45+
error: aborting due to 6 previous errors
5246

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
error: renamed function parameter of trait impl
2+
--> tests/ui-toml/renamed_function_params/renamed_function_params.rs:30:18
3+
|
4+
LL | fn eq(&self, rhs: &Self) -> bool {
5+
| ^^^ help: consider using the default name: `other`
6+
|
7+
= note: `-D clippy::renamed-function-params` implied by `-D warnings`
8+
= help: to override `-D warnings` add `#[allow(clippy::renamed_function_params)]`
9+
10+
error: renamed function parameter of trait impl
11+
--> tests/ui-toml/renamed_function_params/renamed_function_params.rs:34:18
12+
|
13+
LL | fn ne(&self, rhs: &Self) -> bool {
14+
| ^^^ help: consider using the default name: `other`
15+
16+
error: renamed function parameter of trait impl
17+
--> tests/ui-toml/renamed_function_params/renamed_function_params.rs:55:31
18+
|
19+
LL | fn hash<H: Hasher>(&self, states: &mut H) {
20+
| ^^^^^^ help: consider using the default name: `state`
21+
22+
error: renamed function parameters of trait impl
23+
--> tests/ui-toml/renamed_function_params/renamed_function_params.rs:59:30
24+
|
25+
LL | fn hash_slice<H: Hasher>(date: &[Self], states: &mut H) {
26+
| ^^^^ ^^^^^^
27+
|
28+
help: consider using the default names
29+
|
30+
LL | fn hash_slice<H: Hasher>(data: &[Self], state: &mut H) {
31+
| ~~~~ ~~~~~
32+
33+
error: aborting due to 4 previous errors
34+

0 commit comments

Comments
 (0)