]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/new_without_default.rs
Auto merge of #4809 - iankronquist:patch-1, r=flip1995
[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::lint::in_external_macro;
6 use rustc::ty::{self, Ty};
7 use rustc_errors::Applicability;
8 use rustc_hir as hir;
9 use rustc_hir::def_id::DefId;
10 use rustc_hir::HirIdSet;
11 use rustc_lint::{LateContext, LateLintPass, LintContext};
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 use rustc_span::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     #[allow(clippy::too_many_lines)]
97     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
98         if let hir::ItemKind::Impl {
99             of_trait: None, items, ..
100         } = item.kind
101         {
102             for assoc_item in items {
103                 if let hir::AssocItemKind::Method { has_self: false } = assoc_item.kind {
104                     let impl_item = cx.tcx.hir().impl_item(assoc_item.id);
105                     if in_external_macro(cx.sess(), impl_item.span) {
106                         return;
107                     }
108                     if let hir::ImplItemKind::Method(ref sig, _) = impl_item.kind {
109                         let name = impl_item.ident.name;
110                         let id = impl_item.hir_id;
111                         if sig.header.constness == hir::Constness::Const {
112                             // can't be implemented by default
113                             return;
114                         }
115                         if sig.header.unsafety == hir::Unsafety::Unsafe {
116                             // can't be implemented for unsafe new
117                             return;
118                         }
119                         if impl_item.generics.params.iter().any(|gen| match gen.kind {
120                             hir::GenericParamKind::Type { .. } => true,
121                             _ => false,
122                         }) {
123                             // when the result of `new()` depends on a type parameter we should not require
124                             // an
125                             // impl of `Default`
126                             return;
127                         }
128                         if sig.decl.inputs.is_empty() && name == sym!(new) && cx.access_levels.is_reachable(id) {
129                             let self_did = cx.tcx.hir().local_def_id(cx.tcx.hir().get_parent_item(id));
130                             let self_ty = cx.tcx.type_of(self_did);
131                             if_chain! {
132                                 if same_tys(cx, self_ty, return_ty(cx, id));
133                                 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
134                                 then {
135                                     if self.impling_types.is_none() {
136                                         let mut impls = HirIdSet::default();
137                                         cx.tcx.for_each_impl(default_trait_id, |d| {
138                                             if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
139                                                 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
140                                                     impls.insert(hir_id);
141                                                 }
142                                             }
143                                         });
144                                         self.impling_types = Some(impls);
145                                     }
146
147                                     // Check if a Default implementation exists for the Self type, regardless of
148                                     // generics
149                                     if_chain! {
150                                         if let Some(ref impling_types) = self.impling_types;
151                                         if let Some(self_def) = cx.tcx.type_of(self_did).ty_adt_def();
152                                         if self_def.did.is_local();
153                                         then {
154                                             let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_def.did.to_local());
155                                             if impling_types.contains(&self_id) {
156                                                 return;
157                                             }
158                                         }
159                                     }
160
161                                     if let Some(sp) = can_derive_default(self_ty, cx, default_trait_id) {
162                                         span_lint_hir_and_then(
163                                             cx,
164                                             NEW_WITHOUT_DEFAULT,
165                                             id,
166                                             impl_item.span,
167                                             &format!(
168                                                 "you should consider deriving a `Default` implementation for `{}`",
169                                                 self_ty
170                                             ),
171                                             |db| {
172                                                 db.suggest_item_with_attr(
173                                                     cx,
174                                                     sp,
175                                                     "try this",
176                                                     "#[derive(Default)]",
177                                                     Applicability::MaybeIncorrect,
178                                                 );
179                                             });
180                                     } else {
181                                         span_lint_hir_and_then(
182                                             cx,
183                                             NEW_WITHOUT_DEFAULT,
184                                             id,
185                                             impl_item.span,
186                                             &format!(
187                                                 "you should consider adding a `Default` implementation for `{}`",
188                                                 self_ty
189                                             ),
190                                             |db| {
191                                                 db.suggest_prepend_item(
192                                                     cx,
193                                                     item.span,
194                                                     "try this",
195                                                     &create_new_without_default_suggest_msg(self_ty),
196                                                     Applicability::MaybeIncorrect,
197                                                 );
198                                             },
199                                         );
200                                     }
201                                 }
202                             }
203                         }
204                     }
205                 }
206             }
207         }
208     }
209 }
210
211 fn create_new_without_default_suggest_msg(ty: Ty<'_>) -> String {
212     #[rustfmt::skip]
213     format!(
214 "impl Default for {} {{
215     fn default() -> Self {{
216         Self::new()
217     }}
218 }}", ty)
219 }
220
221 fn can_derive_default<'t, 'c>(ty: Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> Option<Span> {
222     match ty.kind {
223         ty::Adt(adt_def, substs) if adt_def.is_struct() => {
224             for field in adt_def.all_fields() {
225                 let f_ty = field.ty(cx.tcx, substs);
226                 if !implements_trait(cx, f_ty, default_trait_id, &[]) {
227                     return None;
228                 }
229             }
230             Some(cx.tcx.def_span(adt_def.did))
231         },
232         _ => None,
233     }
234 }