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