Skip to content

Commit c5a9adc

Browse files
committed
new lint: type_id_on_box
1 parent 3217f8a commit c5a9adc

File tree

7 files changed

+166
-0
lines changed

7 files changed

+166
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5230,6 +5230,7 @@ Released 2018-09-13
52305230
[`trivially_copy_pass_by_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref
52315231
[`try_err`]: https://rust-lang.github.io/rust-clippy/master/index.html#try_err
52325232
[`type_complexity`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_complexity
5233+
[`type_id_on_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_id_on_box
52335234
[`type_repetition_in_bounds`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_repetition_in_bounds
52345235
[`unchecked_duration_subtraction`]: https://rust-lang.github.io/rust-clippy/master/index.html#unchecked_duration_subtraction
52355236
[`undocumented_unsafe_blocks`]: https://rust-lang.github.io/rust-clippy/master/index.html#undocumented_unsafe_blocks

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
403403
crate::methods::SUSPICIOUS_MAP_INFO,
404404
crate::methods::SUSPICIOUS_SPLITN_INFO,
405405
crate::methods::SUSPICIOUS_TO_OWNED_INFO,
406+
crate::methods::TYPE_ID_ON_BOX_INFO,
406407
crate::methods::UNINIT_ASSUMED_INIT_INFO,
407408
crate::methods::UNIT_HASH_INFO,
408409
crate::methods::UNNECESSARY_FILTER_MAP_INFO,

clippy_lints/src/methods/mod.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ mod suspicious_command_arg_space;
8787
mod suspicious_map;
8888
mod suspicious_splitn;
8989
mod suspicious_to_owned;
90+
mod type_id_on_box;
9091
mod uninit_assumed_init;
9192
mod unit_hash;
9293
mod unnecessary_filter_map;
@@ -2922,6 +2923,37 @@ declare_clippy_lint! {
29222923
"use of sort() when sort_unstable() is equivalent"
29232924
}
29242925

2926+
declare_clippy_lint! {
2927+
/// ### What it does
2928+
/// Looks for calls to `<Box<dyn Any> as Any>::type_id`.
2929+
///
2930+
/// ### Why is this bad?
2931+
/// This most certainly does not do what the user expects and is very easy to miss.
2932+
/// Calling `type_id` on a `Box<dyn Any>` calls `type_id` on the `Box<..>` itself,
2933+
/// so this will return the `TypeId` of the `Box<dyn Any>` type (not the type id
2934+
/// of the value referenced by the box!).
2935+
///
2936+
/// ### Example
2937+
/// ```rust,ignore
2938+
/// use std::any::{Any, TypeId};
2939+
///
2940+
/// let any_box: Box<dyn Any> = Box::new(42_i32);
2941+
/// assert_eq!(any_box.type_id(), TypeId::of::<i32>()); // ⚠️ this fails!
2942+
/// ```
2943+
/// Use instead:
2944+
/// ```rust
2945+
/// use std::any::{Any, TypeId};
2946+
///
2947+
/// let any_box: Box<dyn Any> = Box::new(42_i32);
2948+
/// assert_eq!((*any_box).type_id(), TypeId::of::<i32>());
2949+
/// // ^ dereference first, to call `type_id` on `dyn Any`
2950+
/// ```
2951+
#[clippy::version = "1.47.0"]
2952+
pub TYPE_ID_ON_BOX,
2953+
suspicious,
2954+
"calling `.type_id()` on `Box<dyn Any>`"
2955+
}
2956+
29252957
declare_clippy_lint! {
29262958
/// ### What it does
29272959
/// Detects `().hash(_)`.
@@ -3878,6 +3910,9 @@ impl Methods {
38783910
("to_os_string" | "to_path_buf" | "to_vec", []) => {
38793911
implicit_clone::check(cx, name, expr, recv);
38803912
},
3913+
("type_id", []) => {
3914+
type_id_on_box::check(cx, recv, expr.span);
3915+
}
38813916
("unwrap", []) => {
38823917
match method_call(recv) {
38833918
Some(("get", recv, [get_arg], _, _)) => {
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
use crate::methods::TYPE_ID_ON_BOX;
2+
use clippy_utils::diagnostics::span_lint_and_then;
3+
use clippy_utils::source::snippet;
4+
use rustc_errors::Applicability;
5+
use rustc_hir::Expr;
6+
use rustc_lint::LateContext;
7+
use rustc_middle::ty::adjustment::Adjust;
8+
use rustc_middle::ty::adjustment::Adjustment;
9+
use rustc_middle::ty::Ty;
10+
use rustc_middle::ty::{self, ExistentialPredicate};
11+
use rustc_span::{sym, Span};
12+
13+
fn is_dyn_trait(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
14+
if let ty::Dynamic(preds, ..) = ty.kind() {
15+
preds.iter().any(|p| match p.skip_binder() {
16+
ExistentialPredicate::Trait(tr) => cx.tcx.is_diagnostic_item(sym::Any, tr.def_id),
17+
_ => false,
18+
})
19+
} else {
20+
false
21+
}
22+
}
23+
24+
pub(super) fn check(cx: &LateContext<'_>, receiver: &Expr<'_>, call_span: Span) {
25+
let recv_adjusts = cx.typeck_results().expr_adjustments(receiver);
26+
27+
if let Some(Adjustment { target: recv_ty, .. }) = recv_adjusts.last()
28+
&& let ty::Ref(_, ty, _) = recv_ty.kind()
29+
&& let ty::Adt(adt, substs) = ty.kind()
30+
&& adt.is_box()
31+
&& is_dyn_trait(cx, substs.type_at(0))
32+
{
33+
span_lint_and_then(
34+
cx,
35+
TYPE_ID_ON_BOX,
36+
call_span,
37+
"calling `.type_id()` on a `Box<dyn Any>`",
38+
|diag| {
39+
let derefs = recv_adjusts
40+
.iter()
41+
.filter(|adj| matches!(adj.kind, Adjust::Deref(None)))
42+
.count();
43+
44+
let mut sugg = "*".repeat(derefs + 1);
45+
sugg += &snippet(cx, receiver.span, "<expr>");
46+
47+
diag.note(
48+
"this returns the type id of the literal type `Box<dyn Any>` instead of the \
49+
type id of the boxed value, which is most likely not what you want"
50+
)
51+
.note(
52+
"if this is intentional, use `TypeId::of::<Box<dyn Any>>()` instead, \
53+
which makes it more clear"
54+
)
55+
.span_suggestion(
56+
receiver.span,
57+
"consider dereferencing first",
58+
format!("({sugg})"),
59+
Applicability::MaybeIncorrect,
60+
);
61+
},
62+
);
63+
}
64+
}

tests/ui/type_id_on_box.fixed

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
//@run-rustfix
2+
3+
#![warn(clippy::type_id_on_box)]
4+
5+
use std::any::{Any, TypeId};
6+
7+
fn existential() -> impl Any {
8+
Box::new(1) as Box<dyn Any>
9+
}
10+
11+
fn main() {
12+
let any_box: Box<dyn Any> = Box::new(0usize);
13+
let _ = (*any_box).type_id();
14+
let _ = TypeId::of::<Box<dyn Any>>(); // don't lint, user probably explicitly wants to do this
15+
let _ = (*any_box).type_id();
16+
let any_box: &Box<dyn Any> = &(Box::new(0usize) as Box<dyn Any>);
17+
let _ = (**any_box).type_id(); // 2 derefs are needed here
18+
let b = existential();
19+
let _ = b.type_id(); // don't lint
20+
}

tests/ui/type_id_on_box.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
//@run-rustfix
2+
3+
#![warn(clippy::type_id_on_box)]
4+
5+
use std::any::{Any, TypeId};
6+
7+
fn existential() -> impl Any {
8+
Box::new(1) as Box<dyn Any>
9+
}
10+
11+
fn main() {
12+
let any_box: Box<dyn Any> = Box::new(0usize);
13+
let _ = any_box.type_id();
14+
let _ = TypeId::of::<Box<dyn Any>>(); // don't lint, user probably explicitly wants to do this
15+
let _ = (*any_box).type_id();
16+
let any_box: &Box<dyn Any> = &(Box::new(0usize) as Box<dyn Any>);
17+
let _ = any_box.type_id(); // 2 derefs are needed here
18+
let b = existential();
19+
let _ = b.type_id(); // don't lint
20+
}

tests/ui/type_id_on_box.stderr

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
error: calling `.type_id()` on a `Box<dyn Any>`
2+
--> $DIR/type_id_on_box.rs:13:13
3+
|
4+
LL | let _ = any_box.type_id();
5+
| -------^^^^^^^^^^
6+
| |
7+
| help: consider dereferencing first: `(*any_box)`
8+
|
9+
= note: this returns the type id of the literal type `Box<dyn Any>` instead of the type id of the boxed value, which is most likely not what you want
10+
= note: if this is intentional, use `TypeId::of::<Box<dyn Any>>()` instead, which makes it more clear
11+
= note: `-D clippy::type-id-on-box` implied by `-D warnings`
12+
13+
error: calling `.type_id()` on a `Box<dyn Any>`
14+
--> $DIR/type_id_on_box.rs:17:13
15+
|
16+
LL | let _ = any_box.type_id(); // 2 derefs are needed here
17+
| -------^^^^^^^^^^
18+
| |
19+
| help: consider dereferencing first: `(**any_box)`
20+
|
21+
= note: this returns the type id of the literal type `Box<dyn Any>` instead of the type id of the boxed value, which is most likely not what you want
22+
= note: if this is intentional, use `TypeId::of::<Box<dyn Any>>()` instead, which makes it more clear
23+
24+
error: aborting due to 2 previous errors
25+

0 commit comments

Comments
 (0)