]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/new_without_default.rs
Adapt codebase to the tool_lints
[rust.git] / clippy_lints / src / new_without_default.rs
1 use rustc::hir::def_id::DefId;
2 use rustc::hir;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, in_external_macro, LintContext};
4 use rustc::{declare_tool_lint, lint_array};
5 use if_chain::if_chain;
6 use rustc::ty::{self, Ty};
7 use syntax::source_map::Span;
8 use crate::utils::paths;
9 use crate::utils::{get_trait_def_id, implements_trait, return_ty, same_tys, span_lint_and_then};
10 use crate::utils::sugg::DiagnosticBuilderExt;
11
12 /// **What it does:** Checks for types with a `fn new() -> Self` method and no
13 /// implementation of
14 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).
15 ///
16 /// **Why is this bad?** The user might expect to be able to use
17 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
18 /// type can be constructed without arguments.
19 ///
20 /// **Known problems:** Hopefully none.
21 ///
22 /// **Example:**
23 ///
24 /// ```rust
25 /// struct Foo(Bar);
26 ///
27 /// impl Foo {
28 ///     fn new() -> Self {
29 ///         Foo(Bar::new())
30 ///     }
31 /// }
32 /// ```
33 ///
34 /// Instead, use:
35 ///
36 /// ```rust
37 /// struct Foo(Bar);
38 ///
39 /// impl Default for Foo {
40 ///     fn default() -> Self {
41 ///         Foo(Bar::new())
42 ///     }
43 /// }
44 /// ```
45 ///
46 /// You can also have `new()` call `Default::default()`.
47 declare_clippy_lint! {
48     pub NEW_WITHOUT_DEFAULT,
49     style,
50     "`fn new() -> Self` method without `Default` implementation"
51 }
52
53 /// **What it does:** Checks for types with a `fn new() -> Self` method
54 /// and no implementation of
55 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html),
56 /// where the `Default` can be derived by `#[derive(Default)]`.
57 ///
58 /// **Why is this bad?** The user might expect to be able to use
59 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
60 /// type can be constructed without arguments.
61 ///
62 /// **Known problems:** Hopefully none.
63 ///
64 /// **Example:**
65 ///
66 /// ```rust
67 /// struct Foo;
68 ///
69 /// impl Foo {
70 ///     fn new() -> Self {
71 ///         Foo
72 ///     }
73 /// }
74 /// ```
75 ///
76 /// Just prepend `#[derive(Default)]` before the `struct` definition.
77 declare_clippy_lint! {
78     pub NEW_WITHOUT_DEFAULT_DERIVE,
79     style,
80     "`fn new() -> Self` without `#[derive]`able `Default` implementation"
81 }
82
83 #[derive(Copy, Clone)]
84 pub struct NewWithoutDefault;
85
86 impl LintPass for NewWithoutDefault {
87     fn get_lints(&self) -> LintArray {
88         lint_array!(NEW_WITHOUT_DEFAULT, NEW_WITHOUT_DEFAULT_DERIVE)
89     }
90 }
91
92 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
93     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
94         if let hir::ItemKind::Impl(_, _, _, _, None, _, ref items) = item.node {
95             for assoc_item in items {
96                 if let hir::AssociatedItemKind::Method { has_self: false } = assoc_item.kind {
97                     let impl_item = cx.tcx.hir.impl_item(assoc_item.id);
98                     if in_external_macro(cx.sess(), impl_item.span) {
99                         return;
100                     }
101                     if let hir::ImplItemKind::Method(ref sig, _) = impl_item.node {
102                         let name = impl_item.ident.name;
103                         let id = impl_item.id;
104                         if sig.header.constness == hir::Constness::Const {
105                             // can't be implemented by default
106                             return;
107                         }
108                         if impl_item.generics.params.iter().any(|gen| match gen.kind {
109                             hir::GenericParamKind::Type { .. } => true,
110                             _ => false
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 sig.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                                             impl_item.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                                             impl_item.span,
139                                             &format!("you should consider adding a `Default` implementation for `{}`", self_ty),
140                                             |db| {
141                                                 db.suggest_prepend_item(
142                                                     cx,
143                                                     item.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::Adt(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 }