]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/new_without_default.rs
rustup https://github.com/rust-lang/rust/pull/67455
[rust.git] / 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, implements_trait, return_ty, same_tys, span_lint_hir_and_then};
4 use if_chain::if_chain;
5 use rustc::hir;
6 use rustc::hir::def_id::DefId;
7 use rustc::impl_lint_pass;
8 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
9 use rustc::ty::{self, Ty};
10 use rustc::util::nodemap::HirIdSet;
11 use rustc_errors::Applicability;
12 use rustc_session::declare_tool_lint;
13 use syntax::source_map::Span;
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     /// It detects both the case when a manual
21     /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
22     /// implementation is required and also when it can be created with
23     /// `#[derive(Default)]`
24     ///
25     /// **Why is this bad?** The user might expect to be able to use
26     /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
27     /// type can be constructed without arguments.
28     ///
29     /// **Known problems:** Hopefully none.
30     ///
31     /// **Example:**
32     ///
33     /// ```ignore
34     /// struct Foo(Bar);
35     ///
36     /// impl Foo {
37     ///     fn new() -> Self {
38     ///         Foo(Bar::new())
39     ///     }
40     /// }
41     /// ```
42     ///
43     /// Instead, use:
44     ///
45     /// ```ignore
46     /// struct Foo(Bar);
47     ///
48     /// impl Default for Foo {
49     ///     fn default() -> Self {
50     ///         Foo(Bar::new())
51     ///     }
52     /// }
53     /// ```
54     ///
55     /// Or, if
56     /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
57     /// can be derived by `#[derive(Default)]`:
58     ///
59     /// ```rust
60     /// struct Foo;
61     ///
62     /// impl Foo {
63     ///     fn new() -> Self {
64     ///         Foo
65     ///     }
66     /// }
67     /// ```
68     ///
69     /// Instead, use:
70     ///
71     /// ```rust
72     /// #[derive(Default)]
73     /// struct Foo;
74     ///
75     /// impl Foo {
76     ///     fn new() -> Self {
77     ///         Foo
78     ///     }
79     /// }
80     /// ```
81     ///
82     /// You can also have `new()` call `Default::default()`.
83     pub NEW_WITHOUT_DEFAULT,
84     style,
85     "`fn new() -> Self` method without `Default` implementation"
86 }
87
88 #[derive(Clone, Default)]
89 pub struct NewWithoutDefault {
90     impling_types: Option<HirIdSet>,
91 }
92
93 impl_lint_pass!(NewWithoutDefault => [NEW_WITHOUT_DEFAULT]);
94
95 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
96     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
97         if let hir::ItemKind::Impl(_, _, _, _, None, _, ref items) = item.kind {
98             for assoc_item in items {
99                 if let hir::AssocItemKind::Method { has_self: false } = assoc_item.kind {
100                     let impl_item = cx.tcx.hir().impl_item(assoc_item.id);
101                     if in_external_macro(cx.sess(), impl_item.span) {
102                         return;
103                     }
104                     if let hir::ImplItemKind::Method(ref sig, _) = impl_item.kind {
105                         let name = impl_item.ident.name;
106                         let id = impl_item.hir_id;
107                         if sig.header.constness == hir::Constness::Const {
108                             // can't be implemented by default
109                             return;
110                         }
111                         if sig.header.unsafety == hir::Unsafety::Unsafe {
112                             // can't be implemented for unsafe new
113                             return;
114                         }
115                         if impl_item.generics.params.iter().any(|gen| match gen.kind {
116                             hir::GenericParamKind::Type { .. } => true,
117                             _ => false,
118                         }) {
119                             // when the result of `new()` depends on a type parameter we should not require
120                             // an
121                             // impl of `Default`
122                             return;
123                         }
124                         if sig.decl.inputs.is_empty() && name == sym!(new) && cx.access_levels.is_reachable(id) {
125                             let self_did = cx.tcx.hir().local_def_id(cx.tcx.hir().get_parent_item(id));
126                             let self_ty = cx.tcx.type_of(self_did);
127                             if_chain! {
128                                 if same_tys(cx, self_ty, return_ty(cx, id));
129                                 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
130                                 then {
131                                     if self.impling_types.is_none() {
132                                         let mut impls = HirIdSet::default();
133                                         cx.tcx.for_each_impl(default_trait_id, |d| {
134                                             if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
135                                                 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
136                                                     impls.insert(hir_id);
137                                                 }
138                                             }
139                                         });
140                                         self.impling_types = Some(impls);
141                                     }
142
143                                     // Check if a Default implementation exists for the Self type, regardless of
144                                     // generics
145                                     if_chain! {
146                                         if let Some(ref impling_types) = self.impling_types;
147                                         if let Some(self_def) = cx.tcx.type_of(self_did).ty_adt_def();
148                                         if self_def.did.is_local();
149                                         then {
150                                             let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_def.did.to_local());
151                                             if impling_types.contains(&self_id) {
152                                                 return;
153                                             }
154                                         }
155                                     }
156
157                                     if let Some(sp) = can_derive_default(self_ty, cx, default_trait_id) {
158                                         span_lint_hir_and_then(
159                                             cx,
160                                             NEW_WITHOUT_DEFAULT,
161                                             id,
162                                             impl_item.span,
163                                             &format!(
164                                                 "you should consider deriving a `Default` implementation for `{}`",
165                                                 self_ty
166                                             ),
167                                             |db| {
168                                                 db.suggest_item_with_attr(
169                                                     cx,
170                                                     sp,
171                                                     "try this",
172                                                     "#[derive(Default)]",
173                                                     Applicability::MaybeIncorrect,
174                                                 );
175                                             });
176                                     } else {
177                                         span_lint_hir_and_then(
178                                             cx,
179                                             NEW_WITHOUT_DEFAULT,
180                                             id,
181                                             impl_item.span,
182                                             &format!(
183                                                 "you should consider adding a `Default` implementation for `{}`",
184                                                 self_ty
185                                             ),
186                                             |db| {
187                                                 db.suggest_prepend_item(
188                                                     cx,
189                                                     item.span,
190                                                     "try this",
191                                                     &create_new_without_default_suggest_msg(self_ty),
192                                                     Applicability::MaybeIncorrect,
193                                                 );
194                                             },
195                                         );
196                                     }
197                                 }
198                             }
199                         }
200                     }
201                 }
202             }
203         }
204     }
205 }
206
207 fn create_new_without_default_suggest_msg(ty: Ty<'_>) -> String {
208     #[rustfmt::skip]
209     format!(
210 "impl Default for {} {{
211     fn default() -> Self {{
212         Self::new()
213     }}
214 }}", ty)
215 }
216
217 fn can_derive_default<'t, 'c>(ty: Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> Option<Span> {
218     match ty.kind {
219         ty::Adt(adt_def, substs) if adt_def.is_struct() => {
220             for field in adt_def.all_fields() {
221                 let f_ty = field.ty(cx.tcx, substs);
222                 if !implements_trait(cx, f_ty, default_trait_id, &[]) {
223                     return None;
224                 }
225             }
226             Some(cx.tcx.def_span(adt_def.did))
227         },
228         _ => None,
229     }
230 }