]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derivable_impls.rs
Auto merge of #9873 - smoelius:move-line-span, r=flip1995
[rust.git] / clippy_lints / src / derivable_impls.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::{is_default_equivalent, peel_blocks};
3 use rustc_errors::Applicability;
4 use rustc_hir::{
5     def::{DefKind, Res},
6     Body, Expr, ExprKind, GenericArg, Impl, ImplItemKind, Item, ItemKind, Node, PathSegment, QPath, TyKind,
7 };
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::sym;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Detects manual `std::default::Default` implementations that are identical to a derived implementation.
15     ///
16     /// ### Why is this bad?
17     /// It is less concise.
18     ///
19     /// ### Example
20     /// ```rust
21     /// struct Foo {
22     ///     bar: bool
23     /// }
24     ///
25     /// impl Default for Foo {
26     ///     fn default() -> Self {
27     ///         Self {
28     ///             bar: false
29     ///         }
30     ///     }
31     /// }
32     /// ```
33     ///
34     /// Use instead:
35     /// ```rust
36     /// #[derive(Default)]
37     /// struct Foo {
38     ///     bar: bool
39     /// }
40     /// ```
41     ///
42     /// ### Known problems
43     /// Derive macros [sometimes use incorrect bounds](https://github.com/rust-lang/rust/issues/26925)
44     /// in generic types and the user defined `impl` may be more generalized or
45     /// specialized than what derive will produce. This lint can't detect the manual `impl`
46     /// has exactly equal bounds, and therefore this lint is disabled for types with
47     /// generic parameters.
48     #[clippy::version = "1.57.0"]
49     pub DERIVABLE_IMPLS,
50     complexity,
51     "manual implementation of the `Default` trait which is equal to a derive"
52 }
53
54 declare_lint_pass!(DerivableImpls => [DERIVABLE_IMPLS]);
55
56 fn is_path_self(e: &Expr<'_>) -> bool {
57     if let ExprKind::Path(QPath::Resolved(_, p)) = e.kind {
58         matches!(p.res, Res::SelfCtor(..) | Res::Def(DefKind::Ctor(..), _))
59     } else {
60         false
61     }
62 }
63
64 impl<'tcx> LateLintPass<'tcx> for DerivableImpls {
65     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
66         if_chain! {
67             if let ItemKind::Impl(Impl {
68                 of_trait: Some(ref trait_ref),
69                 items: [child],
70                 self_ty,
71                 ..
72             }) = item.kind;
73             if !cx.tcx.has_attr(item.def_id.to_def_id(), sym::automatically_derived);
74             if !item.span.from_expansion();
75             if let Some(def_id) = trait_ref.trait_def_id();
76             if cx.tcx.is_diagnostic_item(sym::Default, def_id);
77             if let impl_item_hir = child.id.hir_id();
78             if let Some(Node::ImplItem(impl_item)) = cx.tcx.hir().find(impl_item_hir);
79             if let ImplItemKind::Fn(_, b) = &impl_item.kind;
80             if let Body { value: func_expr, .. } = cx.tcx.hir().body(*b);
81             if let Some(adt_def) = cx.tcx.type_of(item.def_id).ty_adt_def();
82             if let attrs = cx.tcx.hir().attrs(item.hir_id());
83             if !attrs.iter().any(|attr| attr.doc_str().is_some());
84             if let child_attrs = cx.tcx.hir().attrs(impl_item_hir);
85             if !child_attrs.iter().any(|attr| attr.doc_str().is_some());
86             if adt_def.is_struct();
87             then {
88                 if let TyKind::Path(QPath::Resolved(_, p)) = self_ty.kind {
89                     if let Some(PathSegment { args: Some(a), .. }) = p.segments.last() {
90                         for arg in a.args {
91                             if !matches!(arg, GenericArg::Lifetime(_)) {
92                                 return;
93                             }
94                         }
95                     }
96                 }
97                 let should_emit = match peel_blocks(func_expr).kind {
98                     ExprKind::Tup(fields) => fields.iter().all(|e| is_default_equivalent(cx, e)),
99                     ExprKind::Call(callee, args)
100                         if is_path_self(callee) => args.iter().all(|e| is_default_equivalent(cx, e)),
101                     ExprKind::Struct(_, fields, _) => fields.iter().all(|ef| is_default_equivalent(cx, ef.expr)),
102                     _ => false,
103                 };
104
105                 if should_emit {
106                     let struct_span = cx.tcx.def_span(adt_def.did());
107                     span_lint_and_then(
108                         cx,
109                         DERIVABLE_IMPLS,
110                         item.span,
111                         "this `impl` can be derived",
112                         |diag| {
113                             diag.span_suggestion_hidden(
114                                 item.span,
115                                 "remove the manual implementation...",
116                                 String::new(),
117                                 Applicability::MachineApplicable
118                             );
119                             diag.span_suggestion(
120                                 struct_span.shrink_to_lo(),
121                                 "...and instead derive it",
122                                 "#[derive(Default)]\n".to_string(),
123                                 Applicability::MachineApplicable
124                             );
125                         }
126                     );
127                 }
128             }
129         }
130     }
131 }