Skip to content

Commit 9428138

Browse files
committed
adds lint to detect construction of unit struct using default
Using `default` to construct a unit struct increases code complexity and adds a function call. This can be avoided by simply removing the call to `default` and simply construct by name.
1 parent 990bbdc commit 9428138

File tree

6 files changed

+170
-0
lines changed

6 files changed

+170
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4582,6 +4582,7 @@ Released 2018-09-13
45824582
[`debug_assert_with_mut_call`]: https://rust-lang.github.io/rust-clippy/master/index.html#debug_assert_with_mut_call
45834583
[`decimal_literal_representation`]: https://rust-lang.github.io/rust-clippy/master/index.html#decimal_literal_representation
45844584
[`declare_interior_mutable_const`]: https://rust-lang.github.io/rust-clippy/master/index.html#declare_interior_mutable_const
4585+
[`default_constructed_unit_struct`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_constructed_unit_struct
45854586
[`default_instead_of_iter_empty`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_instead_of_iter_empty
45864587
[`default_numeric_fallback`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_numeric_fallback
45874588
[`default_trait_access`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_trait_access

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
105105
crate::dbg_macro::DBG_MACRO_INFO,
106106
crate::default::DEFAULT_TRAIT_ACCESS_INFO,
107107
crate::default::FIELD_REASSIGN_WITH_DEFAULT_INFO,
108+
crate::default_constructed_unit_struct::DEFAULT_CONSTRUCTED_UNIT_STRUCT_INFO,
108109
crate::default_instead_of_iter_empty::DEFAULT_INSTEAD_OF_ITER_EMPTY_INFO,
109110
crate::default_numeric_fallback::DEFAULT_NUMERIC_FALLBACK_INFO,
110111
crate::default_union_representation::DEFAULT_UNION_REPRESENTATION_INFO,
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
use clippy_utils::{diagnostics::span_lint_and_sugg, is_from_proc_macro, match_def_path, paths};
2+
use hir::{def::Res, ExprKind};
3+
use rustc_errors::Applicability;
4+
use rustc_hir as hir;
5+
use rustc_lint::{LateContext, LateLintPass};
6+
use rustc_middle::ty;
7+
use rustc_session::{declare_lint_pass, declare_tool_lint};
8+
9+
declare_clippy_lint! {
10+
/// ### What it does
11+
/// Check for construction on unit struct using `default`.
12+
///
13+
/// ### Why is this bad?
14+
/// This adds code complexity and an unnecessary function call.
15+
///
16+
/// ### Example
17+
/// ```rust
18+
/// #[derive(Default)]
19+
/// struct S<T> {
20+
/// _marker: PhantomData<T>
21+
/// }
22+
///
23+
/// let _: S<i32> = S {
24+
/// _marker: PhantomData::default()
25+
/// };
26+
/// ```
27+
/// Use instead:
28+
/// ```rust
29+
/// let _: S<i32> = Something {
30+
/// _marker: PhantomData
31+
/// }
32+
/// ```
33+
#[clippy::version = "1.71.0"]
34+
pub DEFAULT_CONSTRUCTED_UNIT_STRUCT,
35+
complexity,
36+
"unit structs can be contructed without calling `default`"
37+
}
38+
declare_lint_pass!(DefaultConstructedUnitStruct => [DEFAULT_CONSTRUCTED_UNIT_STRUCT]);
39+
40+
impl LateLintPass<'_> for DefaultConstructedUnitStruct {
41+
fn check_expr<'tcx>(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
42+
if_chain!(
43+
// make sure we have a call to `Default::default`
44+
if let hir::ExprKind::Call(fn_expr, &[]) = expr.kind;
45+
if let ExprKind::Path(ref qpath) = fn_expr.kind;
46+
if let Res::Def(_, def_id) = cx.qpath_res(qpath, fn_expr.hir_id);
47+
if match_def_path(cx, def_id, &paths::DEFAULT_TRAIT_METHOD);
48+
// make sure we have a struct with no fields (unit struct)
49+
if let ty::Adt(def, ..) = cx.typeck_results().expr_ty(expr).kind();
50+
if def.is_struct() && def.is_payloadfree()
51+
&& !def.non_enum_variant().is_field_list_non_exhaustive()
52+
&& !is_from_proc_macro(cx, expr);
53+
then {
54+
span_lint_and_sugg(
55+
cx,
56+
DEFAULT_CONSTRUCTED_UNIT_STRUCT,
57+
qpath.last_segment_span(),
58+
"Use of `default` to create a unit struct.",
59+
"remove this call to `default`",
60+
String::new(),
61+
Applicability::MachineApplicable,
62+
)
63+
}
64+
);
65+
}
66+
}

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ mod crate_in_macro_def;
9494
mod create_dir;
9595
mod dbg_macro;
9696
mod default;
97+
mod default_constructed_unit_struct;
9798
mod default_instead_of_iter_empty;
9899
mod default_numeric_fallback;
99100
mod default_union_representation;
@@ -970,6 +971,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
970971
store.register_late_pass(|_| Box::new(manual_slice_size_calculation::ManualSliceSizeCalculation));
971972
store.register_early_pass(|| Box::new(suspicious_doc_comments::SuspiciousDocComments));
972973
store.register_late_pass(|_| Box::new(items_after_test_module::ItemsAfterTestModule));
974+
store.register_late_pass(|_| Box::new(default_constructed_unit_struct::DefaultConstructedUnitStruct));
973975
// add lints here, do not remove this comment, it's used in `new_lint`
974976
}
975977

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#![allow(unused)]
2+
#![warn(clippy::default_constructed_unit_struct)]
3+
use std::marker::PhantomData;
4+
5+
#[derive(Default)]
6+
struct UnitStruct;
7+
8+
#[derive(Default)]
9+
struct TupleStruct(usize);
10+
11+
// no lint for derived impl
12+
#[derive(Default)]
13+
struct NormalStruct {
14+
inner: PhantomData<usize>,
15+
}
16+
17+
struct NonDefaultStruct;
18+
19+
impl NonDefaultStruct {
20+
fn default() -> Self {
21+
Self
22+
}
23+
}
24+
25+
#[derive(Default)]
26+
enum SomeEnum {
27+
#[default]
28+
Unit,
29+
Tuple(UnitStruct),
30+
Struct {
31+
inner: usize,
32+
},
33+
}
34+
35+
impl NormalStruct {
36+
fn new() -> Self {
37+
// should lint
38+
Self {
39+
inner: PhantomData::default(),
40+
}
41+
}
42+
}
43+
44+
#[derive(Default)]
45+
struct GenericStruct<T> {
46+
t: T,
47+
}
48+
49+
impl<T: Default> GenericStruct<T> {
50+
fn new() -> Self {
51+
// should not lint
52+
Self { t: T::default() }
53+
}
54+
}
55+
56+
#[derive(Default)]
57+
#[non_exhaustive]
58+
struct NonExhaustiveStruct;
59+
60+
fn main() {
61+
// should lint
62+
let _ = PhantomData::<usize>::default();
63+
let _: PhantomData<i32> = PhantomData::default();
64+
let _ = UnitStruct::default();
65+
66+
// should not lint
67+
let _ = TupleStruct::default();
68+
let _ = NormalStruct::default();
69+
let _ = NonExhaustiveStruct::default();
70+
let _ = SomeEnum::default();
71+
let _ = NonDefaultStruct::default();
72+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
error: Use of `default` to create a unit struct.
2+
--> $DIR/default_constructed_unit_struct.rs:39:33
3+
|
4+
LL | inner: PhantomData::default(),
5+
| ^^^^^^^ help: remove this call to `default`
6+
|
7+
= note: `-D clippy::default-constructed-unit-struct` implied by `-D warnings`
8+
9+
error: Use of `default` to create a unit struct.
10+
--> $DIR/default_constructed_unit_struct.rs:62:35
11+
|
12+
LL | let _ = PhantomData::<usize>::default();
13+
| ^^^^^^^ help: remove this call to `default`
14+
15+
error: Use of `default` to create a unit struct.
16+
--> $DIR/default_constructed_unit_struct.rs:63:44
17+
|
18+
LL | let _: PhantomData<i32> = PhantomData::default();
19+
| ^^^^^^^ help: remove this call to `default`
20+
21+
error: Use of `default` to create a unit struct.
22+
--> $DIR/default_constructed_unit_struct.rs:64:25
23+
|
24+
LL | let _ = UnitStruct::default();
25+
| ^^^^^^^ help: remove this call to `default`
26+
27+
error: aborting due to 4 previous errors
28+

0 commit comments

Comments
 (0)