]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/new_without_default.rs
Fix #2196
[rust.git] / clippy_lints / src / new_without_default.rs
1 use rustc::hir::def_id::DefId;
2 use rustc::hir;
3 use rustc::lint::*;
4 use rustc::ty::{self, Ty};
5 use syntax::codemap::Span;
6 use utils::paths;
7 use utils::{get_trait_def_id, implements_trait, in_external_macro, return_ty, same_tys, span_lint_and_then};
8 use utils::sugg::DiagnosticBuilderExt;
9
10 /// **What it does:** Checks for types with a `fn new() -> Self` method and no
11 /// implementation of
12 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).
13 ///
14 /// **Why is this bad?** The user might expect to be able to use
15 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
16 /// type can be constructed without arguments.
17 ///
18 /// **Known problems:** Hopefully none.
19 ///
20 /// **Example:**
21 ///
22 /// ```rust,ignore
23 /// struct Foo(Bar);
24 ///
25 /// impl Foo {
26 ///     fn new() -> Self {
27 ///         Foo(Bar::new())
28 ///     }
29 /// }
30 /// ```
31 ///
32 /// Instead, use:
33 ///
34 /// ```rust
35 /// struct Foo(Bar);
36 ///
37 /// impl Default for Foo {
38 ///     fn default() -> Self {
39 ///         Foo(Bar::new())
40 ///     }
41 /// }
42 /// ```
43 ///
44 /// You can also have `new()` call `Default::default()`.
45 declare_lint! {
46     pub NEW_WITHOUT_DEFAULT,
47     Warn,
48     "`fn new() -> Self` method without `Default` implementation"
49 }
50
51 /// **What it does:** Checks for types with a `fn new() -> Self` method
52 /// and no implementation of
53 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html),
54 /// where the `Default` can be derived by `#[derive(Default)]`.
55 ///
56 /// **Why is this bad?** The user might expect to be able to use
57 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
58 /// type can be constructed without arguments.
59 ///
60 /// **Known problems:** Hopefully none.
61 ///
62 /// **Example:**
63 ///
64 /// ```rust,ignore
65 /// struct Foo;
66 ///
67 /// impl Foo {
68 ///     fn new() -> Self {
69 ///         Foo
70 ///     }
71 /// }
72 /// ```
73 ///
74 /// Just prepend `#[derive(Default)]` before the `struct` definition.
75 declare_lint! {
76     pub NEW_WITHOUT_DEFAULT_DERIVE,
77     Warn,
78     "`fn new() -> Self` without `#[derive]`able `Default` implementation"
79 }
80
81 #[derive(Copy, Clone)]
82 pub struct NewWithoutDefault;
83
84 impl LintPass for NewWithoutDefault {
85     fn get_lints(&self) -> LintArray {
86         lint_array!(NEW_WITHOUT_DEFAULT, NEW_WITHOUT_DEFAULT_DERIVE)
87     }
88 }
89
90 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
91     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
92         if let hir::ItemImpl(_, _, _, _, None, _, ref items) = item.node {
93             for assoc_item in items {
94                 if let hir::AssociatedItemKind::Method { has_self: false } = assoc_item.kind {
95                     let impl_item = cx.tcx.hir.impl_item(assoc_item.id);
96                     if in_external_macro(cx, impl_item.span) {
97                         return;
98                     }
99                     if let hir::ImplItemKind::Method(ref sig, _) = impl_item.node {
100                         let name = impl_item.name;
101                         let span = impl_item.span;
102                         let id = impl_item.id;
103                         let decl = &sig.decl;
104                         if sig.constness == hir::Constness::Const {
105                             // can't be implemented by default
106                             return;
107                         }
108                         if !impl_item.generics
109                             .ty_params
110                             .is_empty()
111                         {
112                             // when the result of `new()` depends on a type parameter we should not require
113                             // an
114                             // impl of `Default`
115                             return;
116                         }
117                         if decl.inputs.is_empty() && name == "new" && cx.access_levels.is_reachable(id) {
118                             let self_ty = cx.tcx
119                                 .type_of(cx.tcx.hir.local_def_id(cx.tcx.hir.get_parent(id)));
120                             if_chain! {
121                                 if same_tys(cx, self_ty, return_ty(cx, id));
122                                 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
123                                 if !implements_trait(cx, self_ty, default_trait_id, &[]);
124                                 then {
125                                     if let Some(sp) = can_derive_default(self_ty, cx, default_trait_id) {
126                                         span_lint_and_then(
127                                             cx,
128                                             NEW_WITHOUT_DEFAULT_DERIVE,
129                                             span,
130                                             &format!("you should consider deriving a `Default` implementation for `{}`", self_ty),
131                                             |db| {
132                                                 db.suggest_item_with_attr(cx, sp, "try this", "#[derive(Default)]");
133                                             });
134                                     } else {
135                                         span_lint_and_then(
136                                             cx,
137                                             NEW_WITHOUT_DEFAULT,
138                                             span,
139                                             &format!("you should consider adding a `Default` implementation for `{}`", self_ty),
140                                             |db| {
141                                                 db.suggest_prepend_item(
142                                                     cx,
143                                                     span,
144                                                     "try this",
145                                                     &create_new_without_default_suggest_msg(self_ty),
146                                                 );
147                                             },
148                                         );
149                                     }
150                                 }
151                             }
152                         }
153                     }
154                 }
155             }
156         }
157     }
158 }
159
160 fn create_new_without_default_suggest_msg(ty: Ty) -> String {
161     #[rustfmt_skip]
162     format!(
163 "impl Default for {} {{
164     fn default() -> Self {{
165         Self::new()
166     }}
167 }}", ty)
168 }
169
170 fn can_derive_default<'t, 'c>(ty: Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> Option<Span> {
171     match ty.sty {
172         ty::TyAdt(adt_def, substs) if adt_def.is_struct() => {
173             for field in adt_def.all_fields() {
174                 let f_ty = field.ty(cx.tcx, substs);
175                 if !implements_trait(cx, f_ty, default_trait_id, &[]) {
176                     return None;
177                 }
178             }
179             Some(cx.tcx.def_span(adt_def.did))
180         },
181         _ => None,
182     }
183 }