]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derivable_impls.rs
Auto merge of #7638 - xFrednet:7569-avoid-indexing-in-clippy, r=Manishearth
[rust.git] / clippy_lints / src / derivable_impls.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::{in_macro, is_automatically_derived, is_default_equivalent, remove_blocks};
3 use rustc_hir::{
4     def::{DefKind, Res},
5     Body, Expr, ExprKind, Impl, ImplItemKind, Item, ItemKind, Node, QPath,
6 };
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty::TypeFoldable;
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 std::default::Default for Foo {
26     ///     fn default() -> Self {
27     ///         Self {
28     ///             bar: false
29     ///         }
30     ///     }
31     /// }
32     /// ```
33     ///
34     /// Could be written as:
35     ///
36     /// ```rust
37     /// #[derive(Default)]
38     /// struct Foo {
39     ///     bar: bool
40     /// }
41     /// ```
42     ///
43     /// ### Known problems
44     /// Derive macros [sometimes use incorrect bounds](https://github.com/rust-lang/rust/issues/26925)
45     /// in generic types and the user defined `impl` maybe is more generalized or
46     /// specialized than what derive will produce. This lint can't detect the manual `impl`
47     /// has exactly equal bounds, and therefore this lint is disabled for types with
48     /// generic parameters.
49     ///
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                 ..
72             }) = item.kind;
73             if let attrs = cx.tcx.hir().attrs(item.hir_id());
74             if !is_automatically_derived(attrs);
75             if !in_macro(item.span);
76             if let Some(def_id) = trait_ref.trait_def_id();
77             if cx.tcx.is_diagnostic_item(sym::Default, def_id);
78             if let impl_item_hir = child.id.hir_id();
79             if let Some(Node::ImplItem(impl_item)) = cx.tcx.hir().find(impl_item_hir);
80             if let ImplItemKind::Fn(_, b) = &impl_item.kind;
81             if let Body { value: func_expr, .. } = cx.tcx.hir().body(*b);
82             if let Some(adt_def) = cx.tcx.type_of(item.def_id).ty_adt_def();
83             then {
84                 if cx.tcx.type_of(item.def_id).definitely_has_param_types_or_consts(cx.tcx) {
85                     return;
86                 }
87                 let should_emit = match remove_blocks(func_expr).kind {
88                     ExprKind::Tup(fields) => fields.iter().all(|e| is_default_equivalent(cx, e)),
89                     ExprKind::Call(callee, args)
90                         if is_path_self(callee) => args.iter().all(|e| is_default_equivalent(cx, e)),
91                     ExprKind::Struct(_, fields, _) => fields.iter().all(|ef| is_default_equivalent(cx, ef.expr)),
92                     _ => false,
93                 };
94                 if should_emit {
95                     let path_string = cx.tcx.def_path_str(adt_def.did);
96                     span_lint_and_help(
97                         cx,
98                         DERIVABLE_IMPLS,
99                         item.span,
100                         "this `impl` can be derived",
101                         None,
102                         &format!("try annotating `{}` with `#[derive(Default)]`", path_string),
103                     );
104                 }
105             }
106         }
107     }
108 }