]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/new_without_default.rs
Rollup merge of #73418 - doctorn:variants-intrinsic, r=kennytm
[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<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
60     #[allow(clippy::too_many_lines)]
61     fn check_item(&mut self, cx: &LateContext<'a, '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.generics.params.iter().any(|gen| match gen.kind {
84                             hir::GenericParamKind::Type { .. } => true,
85                             _ => false,
86                         }) {
87                             // when the result of `new()` depends on a type parameter we should not require
88                             // an
89                             // impl of `Default`
90                             return;
91                         }
92                         if sig.decl.inputs.is_empty() && name == sym!(new) && cx.access_levels.is_reachable(id) {
93                             let self_def_id = cx.tcx.hir().local_def_id(cx.tcx.hir().get_parent_item(id));
94                             let self_ty = cx.tcx.type_of(self_def_id);
95                             if_chain! {
96                                 if TyS::same_type(self_ty, return_ty(cx, id));
97                                 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
98                                 then {
99                                     if self.impling_types.is_none() {
100                                         let mut impls = HirIdSet::default();
101                                         cx.tcx.for_each_impl(default_trait_id, |d| {
102                                             if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
103                                                 if let Some(local_def_id) = ty_def.did.as_local() {
104                                                     impls.insert(cx.tcx.hir().as_local_hir_id(local_def_id));
105                                                 }
106                                             }
107                                         });
108                                         self.impling_types = Some(impls);
109                                     }
110
111                                     // Check if a Default implementation exists for the Self type, regardless of
112                                     // generics
113                                     if_chain! {
114                                         if let Some(ref impling_types) = self.impling_types;
115                                         if let Some(self_def) = cx.tcx.type_of(self_def_id).ty_adt_def();
116                                         if let Some(self_local_did) = self_def.did.as_local();
117                                         then {
118                                             let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_local_did);
119                                             if impling_types.contains(&self_id) {
120                                                 return;
121                                             }
122                                         }
123                                     }
124
125                                     span_lint_hir_and_then(
126                                         cx,
127                                         NEW_WITHOUT_DEFAULT,
128                                         id,
129                                         impl_item.span,
130                                         &format!(
131                                             "you should consider adding a `Default` implementation for `{}`",
132                                             self_ty
133                                         ),
134                                         |diag| {
135                                             diag.suggest_prepend_item(
136                                                 cx,
137                                                 item.span,
138                                                 "try this",
139                                                 &create_new_without_default_suggest_msg(self_ty),
140                                                 Applicability::MaybeIncorrect,
141                                             );
142                                         },
143                                     );
144                                 }
145                             }
146                         }
147                     }
148                 }
149             }
150         }
151     }
152 }
153
154 fn create_new_without_default_suggest_msg(ty: Ty<'_>) -> String {
155     #[rustfmt::skip]
156     format!(
157 "impl Default for {} {{
158     fn default() -> Self {{
159         Self::new()
160     }}
161 }}", ty)
162 }