]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derivable_impls.rs
Auto merge of #8030 - WaffleLapkin:ignore_trait_assoc_types_type_complexity, r=llogiq
[rust.git] / clippy_lints / src / derivable_impls.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::{is_automatically_derived, is_default_equivalent, peel_blocks};
3 use rustc_hir::{
4     def::{DefKind, Res},
5     Body, Expr, ExprKind, GenericArg, Impl, ImplItemKind, Item, ItemKind, Node, PathSegment, QPath, TyKind,
6 };
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::sym;
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Detects manual `std::default::Default` implementations that are identical to a derived implementation.
14     ///
15     /// ### Why is this bad?
16     /// It is less concise.
17     ///
18     /// ### Example
19     /// ```rust
20     /// struct Foo {
21     ///     bar: bool
22     /// }
23     ///
24     /// impl std::default::Default for Foo {
25     ///     fn default() -> Self {
26     ///         Self {
27     ///             bar: false
28     ///         }
29     ///     }
30     /// }
31     /// ```
32     ///
33     /// Could be written as:
34     ///
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` maybe is 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     ///
49     #[clippy::version = "1.57.0"]
50     pub DERIVABLE_IMPLS,
51     complexity,
52     "manual implementation of the `Default` trait which is equal to a derive"
53 }
54
55 declare_lint_pass!(DerivableImpls => [DERIVABLE_IMPLS]);
56
57 fn is_path_self(e: &Expr<'_>) -> bool {
58     if let ExprKind::Path(QPath::Resolved(_, p)) = e.kind {
59         matches!(p.res, Res::SelfCtor(..) | Res::Def(DefKind::Ctor(..), _))
60     } else {
61         false
62     }
63 }
64
65 impl<'tcx> LateLintPass<'tcx> for DerivableImpls {
66     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
67         if_chain! {
68             if let ItemKind::Impl(Impl {
69                 of_trait: Some(ref trait_ref),
70                 items: [child],
71                 self_ty,
72                 ..
73             }) = item.kind;
74             if let attrs = cx.tcx.hir().attrs(item.hir_id());
75             if !is_automatically_derived(attrs);
76             if !item.span.from_expansion();
77             if let Some(def_id) = trait_ref.trait_def_id();
78             if cx.tcx.is_diagnostic_item(sym::Default, def_id);
79             if let impl_item_hir = child.id.hir_id();
80             if let Some(Node::ImplItem(impl_item)) = cx.tcx.hir().find(impl_item_hir);
81             if let ImplItemKind::Fn(_, b) = &impl_item.kind;
82             if let Body { value: func_expr, .. } = cx.tcx.hir().body(*b);
83             if let Some(adt_def) = cx.tcx.type_of(item.def_id).ty_adt_def();
84             if !attrs.iter().any(|attr| attr.doc_str().is_some());
85             if let child_attrs = cx.tcx.hir().attrs(impl_item_hir);
86             if !child_attrs.iter().any(|attr| attr.doc_str().is_some());
87             if adt_def.is_struct();
88             then {
89                 if let TyKind::Path(QPath::Resolved(_, p)) = self_ty.kind {
90                     if let Some(PathSegment { args: Some(a), .. }) = p.segments.last() {
91                         for arg in a.args {
92                             if !matches!(arg, GenericArg::Lifetime(_)) {
93                                 return;
94                             }
95                         }
96                     }
97                 }
98                 let should_emit = match peel_blocks(func_expr).kind {
99                     ExprKind::Tup(fields) => fields.iter().all(|e| is_default_equivalent(cx, e)),
100                     ExprKind::Call(callee, args)
101                         if is_path_self(callee) => args.iter().all(|e| is_default_equivalent(cx, e)),
102                     ExprKind::Struct(_, fields, _) => fields.iter().all(|ef| is_default_equivalent(cx, ef.expr)),
103                     _ => false,
104                 };
105                 if should_emit {
106                     let path_string = cx.tcx.def_path_str(adt_def.did);
107                     span_lint_and_help(
108                         cx,
109                         DERIVABLE_IMPLS,
110                         item.span,
111                         "this `impl` can be derived",
112                         None,
113                         &format!("try annotating `{}` with `#[derive(Default)]`", path_string),
114                     );
115                 }
116             }
117         }
118     }
119 }