]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/new_without_default.rs
Merge pull request #2821 from mati865/rust-2018-migration
[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 crate::utils::paths;
7 use crate::utils::{get_trait_def_id, implements_trait, in_external_macro, return_ty, same_tys, span_lint_and_then};
8 use crate::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_clippy_lint! {
46     pub NEW_WITHOUT_DEFAULT,
47     style,
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_clippy_lint! {
76     pub NEW_WITHOUT_DEFAULT_DERIVE,
77     style,
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 id = impl_item.id;
102                         if sig.constness == hir::Constness::Const {
103                             // can't be implemented by default
104                             return;
105                         }
106                         if impl_item.generics.params.iter().any(|gen| gen.is_type_param()) {
107                             // when the result of `new()` depends on a type parameter we should not require
108                             // an
109                             // impl of `Default`
110                             return;
111                         }
112                         if sig.decl.inputs.is_empty() && name == "new" && cx.access_levels.is_reachable(id) {
113                             let self_ty = cx.tcx
114                                 .type_of(cx.tcx.hir.local_def_id(cx.tcx.hir.get_parent(id)));
115                             if_chain! {
116                                 if same_tys(cx, self_ty, return_ty(cx, id));
117                                 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
118                                 if !implements_trait(cx, self_ty, default_trait_id, &[]);
119                                 then {
120                                     if let Some(sp) = can_derive_default(self_ty, cx, default_trait_id) {
121                                         span_lint_and_then(
122                                             cx,
123                                             NEW_WITHOUT_DEFAULT_DERIVE,
124                                             impl_item.span,
125                                             &format!("you should consider deriving a `Default` implementation for `{}`", self_ty),
126                                             |db| {
127                                                 db.suggest_item_with_attr(cx, sp, "try this", "#[derive(Default)]");
128                                             });
129                                     } else {
130                                         span_lint_and_then(
131                                             cx,
132                                             NEW_WITHOUT_DEFAULT,
133                                             impl_item.span,
134                                             &format!("you should consider adding a `Default` implementation for `{}`", self_ty),
135                                             |db| {
136                                                 db.suggest_prepend_item(
137                                                     cx,
138                                                     item.span,
139                                                     "try this",
140                                                     &create_new_without_default_suggest_msg(self_ty),
141                                                 );
142                                             },
143                                         );
144                                     }
145                                 }
146                             }
147                         }
148                     }
149                 }
150             }
151         }
152     }
153 }
154
155 fn create_new_without_default_suggest_msg(ty: Ty) -> String {
156     #[cfg_attr(rustfmt, rustfmt_skip)]
157     format!(
158 "impl Default for {} {{
159     fn default() -> Self {{
160         Self::new()
161     }}
162 }}", ty)
163 }
164
165 fn can_derive_default<'t, 'c>(ty: Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> Option<Span> {
166     match ty.sty {
167         ty::TyAdt(adt_def, substs) if adt_def.is_struct() => {
168             for field in adt_def.all_fields() {
169                 let f_ty = field.ty(cx.tcx, substs);
170                 if !implements_trait(cx, f_ty, default_trait_id, &[]) {
171                     return None;
172                 }
173             }
174             Some(cx.tcx.def_span(adt_def.did))
175         },
176         _ => None,
177     }
178 }