1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::msrvs::{self, Msrv};
3 use clippy_utils::source::indent_of;
4 use clippy_utils::{is_default_equivalent, peel_blocks};
5 use rustc_errors::Applicability;
7 def::{CtorKind, CtorOf, DefKind, Res},
8 Body, Expr, ExprKind, GenericArg, Impl, ImplItemKind, Item, ItemKind, Node, PathSegment, QPath, Ty, TyKind,
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::ty::{AdtDef, DefIdTree};
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 declare_clippy_lint! {
17 /// Detects manual `std::default::Default` implementations that are identical to a derived implementation.
19 /// ### Why is this bad?
20 /// It is less concise.
28 /// impl Default for Foo {
29 /// fn default() -> Self {
39 /// #[derive(Default)]
45 /// ### Known problems
46 /// Derive macros [sometimes use incorrect bounds](https://github.com/rust-lang/rust/issues/26925)
47 /// in generic types and the user defined `impl` may be more generalized or
48 /// specialized than what derive will produce. This lint can't detect the manual `impl`
49 /// has exactly equal bounds, and therefore this lint is disabled for types with
50 /// generic parameters.
51 #[clippy::version = "1.57.0"]
54 "manual implementation of the `Default` trait which is equal to a derive"
57 pub struct DerivableImpls {
63 pub fn new(msrv: Msrv) -> Self {
64 DerivableImpls { msrv }
68 impl_lint_pass!(DerivableImpls => [DERIVABLE_IMPLS]);
70 fn is_path_self(e: &Expr<'_>) -> bool {
71 if let ExprKind::Path(QPath::Resolved(_, p)) = e.kind {
72 matches!(p.res, Res::SelfCtor(..) | Res::Def(DefKind::Ctor(..), _))
78 fn check_struct<'tcx>(
79 cx: &LateContext<'tcx>,
85 if let TyKind::Path(QPath::Resolved(_, p)) = self_ty.kind {
86 if let Some(PathSegment { args: Some(a), .. }) = p.segments.last() {
88 if !matches!(arg, GenericArg::Lifetime(_)) {
94 let should_emit = match peel_blocks(func_expr).kind {
95 ExprKind::Tup(fields) => fields.iter().all(|e| is_default_equivalent(cx, e)),
96 ExprKind::Call(callee, args) if is_path_self(callee) => args.iter().all(|e| is_default_equivalent(cx, e)),
97 ExprKind::Struct(_, fields, _) => fields.iter().all(|ef| is_default_equivalent(cx, ef.expr)),
102 let struct_span = cx.tcx.def_span(adt_def.did());
103 span_lint_and_then(cx, DERIVABLE_IMPLS, item.span, "this `impl` can be derived", |diag| {
104 diag.span_suggestion_hidden(
106 "remove the manual implementation...",
108 Applicability::MachineApplicable,
110 diag.span_suggestion(
111 struct_span.shrink_to_lo(),
112 "...and instead derive it",
113 "#[derive(Default)]\n".to_string(),
114 Applicability::MachineApplicable,
120 fn check_enum<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>, func_expr: &Expr<'_>, adt_def: AdtDef<'_>) {
122 if let ExprKind::Path(QPath::Resolved(None, p)) = &peel_blocks(func_expr).kind;
123 if let Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Const), id) = p.res;
124 if let variant_id = cx.tcx.parent(id);
125 if let Some(variant_def) = adt_def.variants().iter().find(|v| v.def_id == variant_id);
126 if variant_def.fields.is_empty();
127 if !variant_def.is_field_list_non_exhaustive();
130 let enum_span = cx.tcx.def_span(adt_def.did());
131 let indent_enum = indent_of(cx, enum_span).unwrap_or(0);
132 let variant_span = cx.tcx.def_span(variant_def.def_id);
133 let indent_variant = indent_of(cx, variant_span).unwrap_or(0);
138 "this `impl` can be derived",
140 diag.span_suggestion_hidden(
142 "remove the manual implementation...",
144 Applicability::MachineApplicable
146 diag.span_suggestion(
147 enum_span.shrink_to_lo(),
148 "...and instead derive it...",
150 "#[derive(Default)]\n{indent}",
151 indent = " ".repeat(indent_enum),
153 Applicability::MachineApplicable
155 diag.span_suggestion(
156 variant_span.shrink_to_lo(),
157 "...and mark the default variant",
159 "#[default]\n{indent}",
160 indent = " ".repeat(indent_variant),
162 Applicability::MachineApplicable
170 impl<'tcx> LateLintPass<'tcx> for DerivableImpls {
171 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
173 if let ItemKind::Impl(Impl {
174 of_trait: Some(ref trait_ref),
179 if !cx.tcx.has_attr(item.owner_id.to_def_id(), sym::automatically_derived);
180 if !item.span.from_expansion();
181 if let Some(def_id) = trait_ref.trait_def_id();
182 if cx.tcx.is_diagnostic_item(sym::Default, def_id);
183 if let impl_item_hir = child.id.hir_id();
184 if let Some(Node::ImplItem(impl_item)) = cx.tcx.hir().find(impl_item_hir);
185 if let ImplItemKind::Fn(_, b) = &impl_item.kind;
186 if let Body { value: func_expr, .. } = cx.tcx.hir().body(*b);
187 if let Some(adt_def) = cx.tcx.type_of(item.owner_id).ty_adt_def();
188 if let attrs = cx.tcx.hir().attrs(item.hir_id());
189 if !attrs.iter().any(|attr| attr.doc_str().is_some());
190 if let child_attrs = cx.tcx.hir().attrs(impl_item_hir);
191 if !child_attrs.iter().any(|attr| attr.doc_str().is_some());
194 if adt_def.is_struct() {
195 check_struct(cx, item, self_ty, func_expr, adt_def);
196 } else if adt_def.is_enum() && self.msrv.meets(msrvs::DEFAULT_ENUM_ATTRIBUTE) {
197 check_enum(cx, item, func_expr, adt_def);
203 extract_msrv_attr!(LateContext);