|
| 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 | +} |
0 commit comments