Skip to content

Commit d606288

Browse files
committed
Add new lint type_param_mismatch
Add new lint for checking if type parameters are consistent between type definitions and impl blocks.
1 parent 1dd5547 commit d606288

7 files changed

+241
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3557,6 +3557,7 @@ Released 2018-09-13
35573557
[`min_max`]: https://rust-lang.github.io/rust-clippy/master/index.html#min_max
35583558
[`misaligned_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#misaligned_transmute
35593559
[`mismatched_target_os`]: https://rust-lang.github.io/rust-clippy/master/index.html#mismatched_target_os
3560+
[`mismatching_type_param_order`]: https://rust-lang.github.io/rust-clippy/master/index.html#mismatching_type_param_order
35603561
[`misrefactored_assign_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#misrefactored_assign_op
35613562
[`missing_const_for_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn
35623563
[`missing_docs_in_private_items`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_docs_in_private_items

clippy_lints/src/lib.register_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,7 @@ store.register_lints(&[
379379
misc_early::UNNEEDED_WILDCARD_PATTERN,
380380
misc_early::UNSEPARATED_LITERAL_SUFFIX,
381381
misc_early::ZERO_PREFIXED_LITERAL,
382+
mismatching_type_param_order::MISMATCHING_TYPE_PARAM_ORDER,
382383
missing_const_for_fn::MISSING_CONST_FOR_FN,
383384
missing_doc::MISSING_DOCS_IN_PRIVATE_ITEMS,
384385
missing_enforced_import_rename::MISSING_ENFORCED_IMPORT_RENAMES,

clippy_lints/src/lib.register_pedantic.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ store.register_group(true, "clippy::pedantic", Some("clippy_pedantic"), vec![
6666
LintId::of(methods::UNNECESSARY_JOIN),
6767
LintId::of(misc::FLOAT_CMP),
6868
LintId::of(misc::USED_UNDERSCORE_BINDING),
69+
LintId::of(mismatching_type_param_order::MISMATCHING_TYPE_PARAM_ORDER),
6970
LintId::of(mut_mut::MUT_MUT),
7071
LintId::of(needless_bitwise_bool::NEEDLESS_BITWISE_BOOL),
7172
LintId::of(needless_continue::NEEDLESS_CONTINUE),

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,7 @@ mod methods;
296296
mod minmax;
297297
mod misc;
298298
mod misc_early;
299+
mod mismatching_type_param_order;
299300
mod missing_const_for_fn;
300301
mod missing_doc;
301302
mod missing_enforced_import_rename;
@@ -909,6 +910,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
909910
store.register_early_pass(|| Box::new(duplicate_mod::DuplicateMod::default()));
910911
store.register_late_pass(|| Box::new(get_first::GetFirst));
911912
store.register_early_pass(|| Box::new(unused_rounding::UnusedRounding));
913+
store.register_late_pass(|| Box::new(mismatching_type_param_order::TypeParamMismatch));
912914
// add lints here, do not remove this comment, it's used in `new_lint`
913915
}
914916

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use rustc_errors::Applicability;
3+
use rustc_hir::def::{DefKind, Res};
4+
use rustc_hir::{GenericArg, Item, ItemKind, QPath, Ty, TyKind};
5+
use rustc_lint::{LateContext, LateLintPass};
6+
use rustc_middle::ty::GenericParamDefKind;
7+
use rustc_session::{declare_lint_pass, declare_tool_lint};
8+
9+
declare_clippy_lint! {
10+
/// ### What it does
11+
/// Checks for type parameters which are positioned inconsistently between
12+
/// a type definition and impl block. Specifically, a paramater in an impl
13+
/// block which has the same name as a parameter in the type def, but is in
14+
/// a different place.
15+
///
16+
/// ### Why is this bad?
17+
/// Type parameters are determined by their position rather than name.
18+
/// Naming type parameters inconsistently may cause you to refer to the
19+
/// wrong type parameter.
20+
///
21+
/// ### Example
22+
/// ```rust
23+
/// struct Foo<A, B> {
24+
/// x: A,
25+
/// y: B,
26+
/// }
27+
/// // inside the impl, B refers to Foo::A
28+
/// impl<B, A> Foo<B, A> {}
29+
/// ```
30+
/// Use instead:
31+
/// ```rust
32+
/// struct Foo<A, B> {
33+
/// x: A,
34+
/// y: B,
35+
/// }
36+
/// impl<A, B> Foo<A, B> {}
37+
/// ```
38+
#[clippy::version = "1.62.0"]
39+
pub MISMATCHING_TYPE_PARAM_ORDER,
40+
pedantic,
41+
"type parameter positioned inconsistently between type def and impl block"
42+
}
43+
declare_lint_pass!(TypeParamMismatch => [MISMATCHING_TYPE_PARAM_ORDER]);
44+
45+
impl<'tcx> LateLintPass<'tcx> for TypeParamMismatch {
46+
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
47+
if_chain! {
48+
if !item.span.from_expansion();
49+
if let ItemKind::Impl(imp) = &item.kind;
50+
if let TyKind::Path(QPath::Resolved(_, path)) = &imp.self_ty.kind;
51+
if let Some(segment) = path.segments.iter().next();
52+
if let Some(generic_args) = segment.args;
53+
if !generic_args.args.is_empty();
54+
then {
55+
// get the name and span of the generic parameters in the Impl
56+
let impl_params = generic_args.args.iter()
57+
.filter_map(|p|
58+
match p {
59+
GenericArg::Type(Ty {kind: TyKind::Path(QPath::Resolved(_, path)), ..}) =>
60+
Some((path.segments[0].ident.to_string(), path.span)),
61+
_ => None,
62+
}
63+
);
64+
65+
// find the type that the Impl is for
66+
// only lint on struct/enum/union for now
67+
let defid = match path.res {
68+
Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, defid) => defid,
69+
_ => return,
70+
};
71+
72+
// get the names of the generic parameters in the type
73+
let type_params = &cx.tcx.generics_of(defid).params;
74+
let type_param_names: Vec<_> = type_params.iter()
75+
.filter_map(|p|
76+
match p.kind {
77+
GenericParamDefKind::Type {..} => Some(p.name.to_string()),
78+
_ => None,
79+
}
80+
).collect();
81+
82+
let type_name = segment.ident;
83+
for (i, (impl_param_name, impl_param_span)) in impl_params.enumerate() {
84+
if mismatch_param_name(i, &impl_param_name, &type_param_names) {
85+
let msg = format!("`{}` has a similarly named generic type parameter `{}` in its declaration, but in a different order",
86+
type_name, impl_param_name);
87+
span_lint_and_sugg(
88+
cx,
89+
MISMATCHING_TYPE_PARAM_ORDER,
90+
impl_param_span,
91+
&msg,
92+
"try",
93+
type_param_names[i].to_string(),
94+
Applicability::MaybeIncorrect
95+
);
96+
}
97+
}
98+
}
99+
}
100+
}
101+
}
102+
103+
// Checks if impl_param_name is the same as one of type_param_names,
104+
// and is in a different position
105+
fn mismatch_param_name(i: usize, impl_param_name: &str, type_param_names: &[String]) -> bool {
106+
for (j, type_param_name) in type_param_names.iter().enumerate() {
107+
if impl_param_name == type_param_name && i != j {
108+
return true;
109+
}
110+
}
111+
false
112+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#![warn(clippy::mismatching_type_param_order)]
2+
#![allow(clippy::blacklisted_name)]
3+
4+
fn main() {
5+
struct Foo<A, B> {
6+
x: A,
7+
y: B,
8+
}
9+
10+
// lint on both params
11+
impl<B, A> Foo<B, A> {}
12+
13+
// lint on the 2nd param
14+
impl<C, A> Foo<C, A> {}
15+
16+
// should not lint
17+
impl<A, B> Foo<A, B> {}
18+
19+
struct FooLifetime<'l, 'm, A, B> {
20+
x: &'l A,
21+
y: &'m B,
22+
}
23+
24+
// should not lint on lifetimes
25+
impl<'m, 'l, B, A> FooLifetime<'m, 'l, B, A> {}
26+
27+
struct Bar {
28+
x: i32,
29+
}
30+
31+
// should not lint
32+
impl Bar {}
33+
34+
// also works for enums
35+
enum FooEnum<A, B, C> {
36+
X(A),
37+
Y(B),
38+
Z(C),
39+
}
40+
41+
impl<C, A, B> FooEnum<C, A, B> {}
42+
43+
// also works for unions
44+
union FooUnion<A: Copy, B>
45+
where
46+
B: Copy,
47+
{
48+
x: A,
49+
y: B,
50+
}
51+
52+
impl<B: Copy, A> FooUnion<B, A> where A: Copy {}
53+
54+
impl<A, B> FooUnion<A, B>
55+
where
56+
A: Copy,
57+
B: Copy,
58+
{
59+
}
60+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
error: `Foo` has a similarly named generic type parameter `B` in its declaration, but in a different order
2+
--> $DIR/mismatching_type_param_order.rs:11:20
3+
|
4+
LL | impl<B, A> Foo<B, A> {}
5+
| ^ help: try: `A`
6+
|
7+
= note: `-D clippy::mismatching-type-param-order` implied by `-D warnings`
8+
9+
error: `Foo` has a similarly named generic type parameter `A` in its declaration, but in a different order
10+
--> $DIR/mismatching_type_param_order.rs:11:23
11+
|
12+
LL | impl<B, A> Foo<B, A> {}
13+
| ^ help: try: `B`
14+
15+
error: `Foo` has a similarly named generic type parameter `A` in its declaration, but in a different order
16+
--> $DIR/mismatching_type_param_order.rs:14:23
17+
|
18+
LL | impl<C, A> Foo<C, A> {}
19+
| ^ help: try: `B`
20+
21+
error: `FooLifetime` has a similarly named generic type parameter `B` in its declaration, but in a different order
22+
--> $DIR/mismatching_type_param_order.rs:25:44
23+
|
24+
LL | impl<'m, 'l, B, A> FooLifetime<'m, 'l, B, A> {}
25+
| ^ help: try: `A`
26+
27+
error: `FooLifetime` has a similarly named generic type parameter `A` in its declaration, but in a different order
28+
--> $DIR/mismatching_type_param_order.rs:25:47
29+
|
30+
LL | impl<'m, 'l, B, A> FooLifetime<'m, 'l, B, A> {}
31+
| ^ help: try: `B`
32+
33+
error: `FooEnum` has a similarly named generic type parameter `C` in its declaration, but in a different order
34+
--> $DIR/mismatching_type_param_order.rs:41:27
35+
|
36+
LL | impl<C, A, B> FooEnum<C, A, B> {}
37+
| ^ help: try: `A`
38+
39+
error: `FooEnum` has a similarly named generic type parameter `A` in its declaration, but in a different order
40+
--> $DIR/mismatching_type_param_order.rs:41:30
41+
|
42+
LL | impl<C, A, B> FooEnum<C, A, B> {}
43+
| ^ help: try: `B`
44+
45+
error: `FooEnum` has a similarly named generic type parameter `B` in its declaration, but in a different order
46+
--> $DIR/mismatching_type_param_order.rs:41:33
47+
|
48+
LL | impl<C, A, B> FooEnum<C, A, B> {}
49+
| ^ help: try: `C`
50+
51+
error: `FooUnion` has a similarly named generic type parameter `B` in its declaration, but in a different order
52+
--> $DIR/mismatching_type_param_order.rs:52:31
53+
|
54+
LL | impl<B: Copy, A> FooUnion<B, A> where A: Copy {}
55+
| ^ help: try: `A`
56+
57+
error: `FooUnion` has a similarly named generic type parameter `A` in its declaration, but in a different order
58+
--> $DIR/mismatching_type_param_order.rs:52:34
59+
|
60+
LL | impl<B: Copy, A> FooUnion<B, A> where A: Copy {}
61+
| ^ help: try: `B`
62+
63+
error: aborting due to 10 previous errors
64+

0 commit comments

Comments
 (0)