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