about summary refs log tree commit diff
diff options
context:
space:
mode:
authorIcxolu <10486322+Icxolu@users.noreply.github.com>2023-04-25 20:44:09 +0200
committerIcxolu <10486322+Icxolu@users.noreply.github.com>2023-04-26 21:12:59 +0200
commit9428138562bad89fc2d7d011fe276cd198e6155a (patch)
treefd779117f0f590547ebf7a0d5f0ad5ee552aaa96
parent990bbdc2bee264291843497cebe59f307c2ed86f (diff)
downloadrust-9428138562bad89fc2d7d011fe276cd198e6155a.tar.gz
rust-9428138562bad89fc2d7d011fe276cd198e6155a.zip
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.
-rw-r--r--CHANGELOG.md1
-rw-r--r--clippy_lints/src/declared_lints.rs1
-rw-r--r--clippy_lints/src/default_constructed_unit_struct.rs66
-rw-r--r--clippy_lints/src/lib.rs2
-rw-r--r--tests/ui/default_constructed_unit_struct.rs72
-rw-r--r--tests/ui/default_constructed_unit_struct.stderr28
6 files changed, 170 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 23f4f97ee07..735ac59758a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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
diff --git a/clippy_lints/src/declared_lints.rs b/clippy_lints/src/declared_lints.rs
index 4aebd0b7d01..bf30f5b52f7 100644
--- a/clippy_lints/src/declared_lints.rs
+++ b/clippy_lints/src/declared_lints.rs
@@ -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,
diff --git a/clippy_lints/src/default_constructed_unit_struct.rs b/clippy_lints/src/default_constructed_unit_struct.rs
new file mode 100644
index 00000000000..a04f7b9d9a9
--- /dev/null
+++ b/clippy_lints/src/default_constructed_unit_struct.rs
@@ -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,
+                )
+            }
+        );
+    }
+}
diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs
index 48dbecc9f6a..9af0b17e27b 100644
--- a/clippy_lints/src/lib.rs
+++ b/clippy_lints/src/lib.rs
@@ -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`
 }
 
diff --git a/tests/ui/default_constructed_unit_struct.rs b/tests/ui/default_constructed_unit_struct.rs
new file mode 100644
index 00000000000..b64da9b863a
--- /dev/null
+++ b/tests/ui/default_constructed_unit_struct.rs
@@ -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();
+}
diff --git a/tests/ui/default_constructed_unit_struct.stderr b/tests/ui/default_constructed_unit_struct.stderr
new file mode 100644
index 00000000000..13439414f4a
--- /dev/null
+++ b/tests/ui/default_constructed_unit_struct.stderr
@@ -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
+