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