]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/derivable_impls.rs
Rollup merge of #105796 - notriddle:notriddle/rustdoc-search-stop-doing-demerits...
[rust.git] / src / tools / clippy / clippy_lints / src / derivable_impls.rs
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;
6 use rustc_hir::{
7     def::{CtorKind, CtorOf, DefKind, Res},
8     Body, Expr, ExprKind, GenericArg, Impl, ImplItemKind, Item, ItemKind, Node, PathSegment, QPath, Ty, TyKind,
9 };
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::ty::{AdtDef, DefIdTree};
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 use rustc_span::sym;
14
15 declare_clippy_lint! {
16     /// ### What it does
17     /// Detects manual `std::default::Default` implementations that are identical to a derived implementation.
18     ///
19     /// ### Why is this bad?
20     /// It is less concise.
21     ///
22     /// ### Example
23     /// ```rust
24     /// struct Foo {
25     ///     bar: bool
26     /// }
27     ///
28     /// impl Default for Foo {
29     ///     fn default() -> Self {
30     ///         Self {
31     ///             bar: false
32     ///         }
33     ///     }
34     /// }
35     /// ```
36     ///
37     /// Use instead:
38     /// ```rust
39     /// #[derive(Default)]
40     /// struct Foo {
41     ///     bar: bool
42     /// }
43     /// ```
44     ///
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"]
52     pub DERIVABLE_IMPLS,
53     complexity,
54     "manual implementation of the `Default` trait which is equal to a derive"
55 }
56
57 pub struct DerivableImpls {
58     msrv: Msrv,
59 }
60
61 impl DerivableImpls {
62     #[must_use]
63     pub fn new(msrv: Msrv) -> Self {
64         DerivableImpls { msrv }
65     }
66 }
67
68 impl_lint_pass!(DerivableImpls => [DERIVABLE_IMPLS]);
69
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(..), _))
73     } else {
74         false
75     }
76 }
77
78 fn check_struct<'tcx>(
79     cx: &LateContext<'tcx>,
80     item: &'tcx Item<'_>,
81     self_ty: &Ty<'_>,
82     func_expr: &Expr<'_>,
83     adt_def: AdtDef<'_>,
84 ) {
85     if let TyKind::Path(QPath::Resolved(_, p)) = self_ty.kind {
86         if let Some(PathSegment { args: Some(a), .. }) = p.segments.last() {
87             for arg in a.args {
88                 if !matches!(arg, GenericArg::Lifetime(_)) {
89                     return;
90                 }
91             }
92         }
93     }
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)),
98         _ => false,
99     };
100
101     if should_emit {
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(
105                 item.span,
106                 "remove the manual implementation...",
107                 String::new(),
108                 Applicability::MachineApplicable,
109             );
110             diag.span_suggestion(
111                 struct_span.shrink_to_lo(),
112                 "...and instead derive it",
113                 "#[derive(Default)]\n".to_string(),
114                 Applicability::MachineApplicable,
115             );
116         });
117     }
118 }
119
120 fn check_enum<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>, func_expr: &Expr<'_>, adt_def: AdtDef<'_>) {
121     if_chain! {
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();
128
129         then {
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);
134             span_lint_and_then(
135                 cx,
136                 DERIVABLE_IMPLS,
137                 item.span,
138                 "this `impl` can be derived",
139                 |diag| {
140                     diag.span_suggestion_hidden(
141                         item.span,
142                         "remove the manual implementation...",
143                         String::new(),
144                         Applicability::MachineApplicable
145                     );
146                     diag.span_suggestion(
147                         enum_span.shrink_to_lo(),
148                         "...and instead derive it...",
149                         format!(
150                             "#[derive(Default)]\n{indent}",
151                             indent = " ".repeat(indent_enum),
152                         ),
153                         Applicability::MachineApplicable
154                     );
155                     diag.span_suggestion(
156                         variant_span.shrink_to_lo(),
157                         "...and mark the default variant",
158                         format!(
159                             "#[default]\n{indent}",
160                             indent = " ".repeat(indent_variant),
161                         ),
162                         Applicability::MachineApplicable
163                     );
164                 }
165             );
166         }
167     }
168 }
169
170 impl<'tcx> LateLintPass<'tcx> for DerivableImpls {
171     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
172         if_chain! {
173             if let ItemKind::Impl(Impl {
174                 of_trait: Some(ref trait_ref),
175                 items: [child],
176                 self_ty,
177                 ..
178             }) = item.kind;
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());
192
193             then {
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);
198                 }
199             }
200         }
201     }
202
203     extract_msrv_attr!(LateContext);
204 }