]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/new_without_default.rs
9cebe4b0be6e1a245f0b1a45ab70c950d5d34163
[rust.git] / clippy_lints / src / new_without_default.rs
1 use rustc::hir::intravisit::FnKind;
2 use rustc::hir::def_id::DefId;
3 use rustc::hir;
4 use rustc::lint::*;
5 use rustc::ty::{self, Ty};
6 use syntax::ast;
7 use syntax::codemap::Span;
8 use utils::paths;
9 use utils::{get_trait_def_id, implements_trait, in_external_macro, return_ty, same_tys, span_lint_and_then};
10 use 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,ignore
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_lint! {
48     pub NEW_WITHOUT_DEFAULT,
49     Warn,
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,ignore
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_lint! {
78     pub NEW_WITHOUT_DEFAULT_DERIVE,
79     Warn,
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_fn(
94         &mut self,
95         cx: &LateContext<'a, 'tcx>,
96         kind: FnKind<'tcx>,
97         decl: &'tcx hir::FnDecl,
98         _: &'tcx hir::Body,
99         span: Span,
100         id: ast::NodeId
101     ) {
102         if in_external_macro(cx, span) {
103             return;
104         }
105
106         if let FnKind::Method(name, sig, _, _) = kind {
107             if sig.constness == hir::Constness::Const {
108                 // can't be implemented by default
109                 return;
110             }
111             if decl.inputs.is_empty() && name == "new" && cx.access_levels.is_reachable(id) {
112                 let self_ty = cx.tcx
113                     .type_of(cx.tcx.hir.local_def_id(cx.tcx.hir.get_parent(id)));
114                 if_let_chain!{[
115                     same_tys(cx, self_ty, return_ty(cx, id)),
116                     let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT),
117                     !implements_trait(cx, self_ty, default_trait_id, &[])
118                 ], {
119                     if let Some(sp) = can_derive_default(self_ty, cx, default_trait_id) {
120                         span_lint_and_then(cx,
121                                            NEW_WITHOUT_DEFAULT_DERIVE, span,
122                                            &format!("you should consider deriving a \
123                                                      `Default` implementation for `{}`",
124                                                     self_ty),
125                                            |db| {
126                             db.suggest_item_with_attr(cx, sp, "try this", "#[derive(Default)]");
127                         });
128                     } else {
129                         span_lint_and_then(cx,
130                                            NEW_WITHOUT_DEFAULT, span,
131                                            &format!("you should consider adding a \
132                                                     `Default` implementation for `{}`",
133                                                     self_ty),
134                                            |db| {
135                         db.suggest_prepend_item(cx,
136                                                   span,
137                                                   "try this",
138                                                   &format!(
139 "impl Default for {} {{
140     fn default() -> Self {{
141         Self::new()
142     }}
143 }}",
144                                                            self_ty));
145                         });
146                     }
147                 }}
148             }
149         }
150     }
151 }
152
153 fn can_derive_default<'t, 'c>(ty: Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> Option<Span> {
154     match ty.sty {
155         ty::TyAdt(adt_def, substs) if adt_def.is_struct() => {
156             for field in adt_def.all_fields() {
157                 let f_ty = field.ty(cx.tcx, substs);
158                 if !implements_trait(cx, f_ty, default_trait_id, &[]) {
159                     return None;
160                 }
161             }
162             cx.tcx.hir.span_if_local(adt_def.did)
163         },
164         _ => None,
165     }
166 }