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.
This commit is contained in:
Icxolu 2023-04-25 20:44:09 +02:00
parent 990bbdc2be
commit 9428138562
6 changed files with 170 additions and 0 deletions

View File

@ -4582,6 +4582,7 @@ Released 2018-09-13
[`debug_assert_with_mut_call`]: https://rust-lang.github.io/rust-clippy/master/index.html#debug_assert_with_mut_call
[`decimal_literal_representation`]: https://rust-lang.github.io/rust-clippy/master/index.html#decimal_literal_representation
[`declare_interior_mutable_const`]: https://rust-lang.github.io/rust-clippy/master/index.html#declare_interior_mutable_const
[`default_constructed_unit_struct`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_constructed_unit_struct
[`default_instead_of_iter_empty`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_instead_of_iter_empty
[`default_numeric_fallback`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_numeric_fallback
[`default_trait_access`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_trait_access

View File

@ -105,6 +105,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
crate::dbg_macro::DBG_MACRO_INFO,
crate::default::DEFAULT_TRAIT_ACCESS_INFO,
crate::default::FIELD_REASSIGN_WITH_DEFAULT_INFO,
crate::default_constructed_unit_struct::DEFAULT_CONSTRUCTED_UNIT_STRUCT_INFO,
crate::default_instead_of_iter_empty::DEFAULT_INSTEAD_OF_ITER_EMPTY_INFO,
crate::default_numeric_fallback::DEFAULT_NUMERIC_FALLBACK_INFO,
crate::default_union_representation::DEFAULT_UNION_REPRESENTATION_INFO,

View File

@ -0,0 +1,66 @@
use clippy_utils::{diagnostics::span_lint_and_sugg, is_from_proc_macro, match_def_path, paths};
use hir::{def::Res, ExprKind};
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
declare_clippy_lint! {
/// ### What it does
/// Check for construction on unit struct using `default`.
///
/// ### Why is this bad?
/// This adds code complexity and an unnecessary function call.
///
/// ### Example
/// ```rust
/// #[derive(Default)]
/// struct S<T> {
/// _marker: PhantomData<T>
/// }
///
/// let _: S<i32> = S {
/// _marker: PhantomData::default()
/// };
/// ```
/// Use instead:
/// ```rust
/// let _: S<i32> = Something {
/// _marker: PhantomData
/// }
/// ```
#[clippy::version = "1.71.0"]
pub DEFAULT_CONSTRUCTED_UNIT_STRUCT,
complexity,
"unit structs can be contructed without calling `default`"
}
declare_lint_pass!(DefaultConstructedUnitStruct => [DEFAULT_CONSTRUCTED_UNIT_STRUCT]);
impl LateLintPass<'_> for DefaultConstructedUnitStruct {
fn check_expr<'tcx>(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
if_chain!(
// make sure we have a call to `Default::default`
if let hir::ExprKind::Call(fn_expr, &[]) = expr.kind;
if let ExprKind::Path(ref qpath) = fn_expr.kind;
if let Res::Def(_, def_id) = cx.qpath_res(qpath, fn_expr.hir_id);
if match_def_path(cx, def_id, &paths::DEFAULT_TRAIT_METHOD);
// make sure we have a struct with no fields (unit struct)
if let ty::Adt(def, ..) = cx.typeck_results().expr_ty(expr).kind();
if def.is_struct() && def.is_payloadfree()
&& !def.non_enum_variant().is_field_list_non_exhaustive()
&& !is_from_proc_macro(cx, expr);
then {
span_lint_and_sugg(
cx,
DEFAULT_CONSTRUCTED_UNIT_STRUCT,
qpath.last_segment_span(),
"Use of `default` to create a unit struct.",
"remove this call to `default`",
String::new(),
Applicability::MachineApplicable,
)
}
);
}
}

View File

@ -94,6 +94,7 @@ mod crate_in_macro_def;
mod create_dir;
mod dbg_macro;
mod default;
mod default_constructed_unit_struct;
mod default_instead_of_iter_empty;
mod default_numeric_fallback;
mod default_union_representation;
@ -970,6 +971,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
store.register_late_pass(|_| Box::new(manual_slice_size_calculation::ManualSliceSizeCalculation));
store.register_early_pass(|| Box::new(suspicious_doc_comments::SuspiciousDocComments));
store.register_late_pass(|_| Box::new(items_after_test_module::ItemsAfterTestModule));
store.register_late_pass(|_| Box::new(default_constructed_unit_struct::DefaultConstructedUnitStruct));
// add lints here, do not remove this comment, it's used in `new_lint`
}

View File

@ -0,0 +1,72 @@
#![allow(unused)]
#![warn(clippy::default_constructed_unit_struct)]
use std::marker::PhantomData;
#[derive(Default)]
struct UnitStruct;
#[derive(Default)]
struct TupleStruct(usize);
// no lint for derived impl
#[derive(Default)]
struct NormalStruct {
inner: PhantomData<usize>,
}
struct NonDefaultStruct;
impl NonDefaultStruct {
fn default() -> Self {
Self
}
}
#[derive(Default)]
enum SomeEnum {
#[default]
Unit,
Tuple(UnitStruct),
Struct {
inner: usize,
},
}
impl NormalStruct {
fn new() -> Self {
// should lint
Self {
inner: PhantomData::default(),
}
}
}
#[derive(Default)]
struct GenericStruct<T> {
t: T,
}
impl<T: Default> GenericStruct<T> {
fn new() -> Self {
// should not lint
Self { t: T::default() }
}
}
#[derive(Default)]
#[non_exhaustive]
struct NonExhaustiveStruct;
fn main() {
// should lint
let _ = PhantomData::<usize>::default();
let _: PhantomData<i32> = PhantomData::default();
let _ = UnitStruct::default();
// should not lint
let _ = TupleStruct::default();
let _ = NormalStruct::default();
let _ = NonExhaustiveStruct::default();
let _ = SomeEnum::default();
let _ = NonDefaultStruct::default();
}

View File

@ -0,0 +1,28 @@
error: Use of `default` to create a unit struct.
--> $DIR/default_constructed_unit_struct.rs:39:33
|
LL | inner: PhantomData::default(),
| ^^^^^^^ help: remove this call to `default`
|
= note: `-D clippy::default-constructed-unit-struct` implied by `-D warnings`
error: Use of `default` to create a unit struct.
--> $DIR/default_constructed_unit_struct.rs:62:35
|
LL | let _ = PhantomData::<usize>::default();
| ^^^^^^^ help: remove this call to `default`
error: Use of `default` to create a unit struct.
--> $DIR/default_constructed_unit_struct.rs:63:44
|
LL | let _: PhantomData<i32> = PhantomData::default();
| ^^^^^^^ help: remove this call to `default`
error: Use of `default` to create a unit struct.
--> $DIR/default_constructed_unit_struct.rs:64:25
|
LL | let _ = UnitStruct::default();
| ^^^^^^^ help: remove this call to `default`
error: aborting due to 4 previous errors