]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/new_without_default.rs
Auto merge of #78420 - estebank:suggest-assoc-fn, r=petrochenkov
[rust.git] / src / tools / clippy / clippy_lints / src / new_without_default.rs
1 use crate::utils::paths;
2 use crate::utils::sugg::DiagnosticBuilderExt;
3 use crate::utils::{get_trait_def_id, return_ty, span_lint_hir_and_then};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir as hir;
7 use rustc_hir::HirIdSet;
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_middle::ty::{Ty, TyS};
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks for types with a `fn new() -> Self` method and no
15     /// implementation of
16     /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).
17     ///
18     /// **Why is this bad?** The user might expect to be able to use
19     /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
20     /// type can be constructed without arguments.
21     ///
22     /// **Known problems:** Hopefully none.
23     ///
24     /// **Example:**
25     ///
26     /// ```ignore
27     /// struct Foo(Bar);
28     ///
29     /// impl Foo {
30     ///     fn new() -> Self {
31     ///         Foo(Bar::new())
32     ///     }
33     /// }
34     /// ```
35     ///
36     /// To fix the lint, add a `Default` implementation that delegates to `new`:
37     ///
38     /// ```ignore
39     /// struct Foo(Bar);
40     ///
41     /// impl Default for Foo {
42     ///     fn default() -> Self {
43     ///         Foo::new()
44     ///     }
45     /// }
46     /// ```
47     pub NEW_WITHOUT_DEFAULT,
48     style,
49     "`fn new() -> Self` method without `Default` implementation"
50 }
51
52 #[derive(Clone, Default)]
53 pub struct NewWithoutDefault {
54     impling_types: Option<HirIdSet>,
55 }
56
57 impl_lint_pass!(NewWithoutDefault => [NEW_WITHOUT_DEFAULT]);
58
59 impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault {
60     #[allow(clippy::too_many_lines)]
61     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
62         if let hir::ItemKind::Impl {
63             of_trait: None, items, ..
64         } = item.kind
65         {
66             for assoc_item in items {
67                 if let hir::AssocItemKind::Fn { has_self: false } = assoc_item.kind {
68                     let impl_item = cx.tcx.hir().impl_item(assoc_item.id);
69                     if in_external_macro(cx.sess(), impl_item.span) {
70                         return;
71                     }
72                     if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind {
73                         let name = impl_item.ident.name;
74                         let id = impl_item.hir_id;
75                         if sig.header.constness == hir::Constness::Const {
76                             // can't be implemented by default
77                             return;
78                         }
79                         if sig.header.unsafety == hir::Unsafety::Unsafe {
80                             // can't be implemented for unsafe new
81                             return;
82                         }
83                         if impl_item
84                             .generics
85                             .params
86                             .iter()
87                             .any(|gen| matches!(gen.kind, hir::GenericParamKind::Type { .. }))
88                         {
89                             // when the result of `new()` depends on a type parameter we should not require
90                             // an
91                             // impl of `Default`
92                             return;
93                         }
94                         if sig.decl.inputs.is_empty() && name == sym!(new) && cx.access_levels.is_reachable(id) {
95                             let self_def_id = cx.tcx.hir().local_def_id(cx.tcx.hir().get_parent_item(id));
96                             let self_ty = cx.tcx.type_of(self_def_id);
97                             if_chain! {
98                                 if TyS::same_type(self_ty, return_ty(cx, id));
99                                 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
100                                 then {
101                                     if self.impling_types.is_none() {
102                                         let mut impls = HirIdSet::default();
103                                         cx.tcx.for_each_impl(default_trait_id, |d| {
104                                             if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
105                                                 if let Some(local_def_id) = ty_def.did.as_local() {
106                                                     impls.insert(cx.tcx.hir().local_def_id_to_hir_id(local_def_id));
107                                                 }
108                                             }
109                                         });
110                                         self.impling_types = Some(impls);
111                                     }
112
113                                     // Check if a Default implementation exists for the Self type, regardless of
114                                     // generics
115                                     if_chain! {
116                                         if let Some(ref impling_types) = self.impling_types;
117                                         if let Some(self_def) = cx.tcx.type_of(self_def_id).ty_adt_def();
118                                         if let Some(self_local_did) = self_def.did.as_local();
119                                         then {
120                                             let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_local_did);
121                                             if impling_types.contains(&self_id) {
122                                                 return;
123                                             }
124                                         }
125                                     }
126
127                                     span_lint_hir_and_then(
128                                         cx,
129                                         NEW_WITHOUT_DEFAULT,
130                                         id,
131                                         impl_item.span,
132                                         &format!(
133                                             "you should consider adding a `Default` implementation for `{}`",
134                                             self_ty
135                                         ),
136                                         |diag| {
137                                             diag.suggest_prepend_item(
138                                                 cx,
139                                                 item.span,
140                                                 "try this",
141                                                 &create_new_without_default_suggest_msg(self_ty),
142                                                 Applicability::MaybeIncorrect,
143                                             );
144                                         },
145                                     );
146                                 }
147                             }
148                         }
149                     }
150                 }
151             }
152         }
153     }
154 }
155
156 fn create_new_without_default_suggest_msg(ty: Ty<'_>) -> String {
157     #[rustfmt::skip]
158     format!(
159 "impl Default for {} {{
160     fn default() -> Self {{
161         Self::new()
162     }}
163 }}", ty)
164 }