]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/new_without_default.rs
Merge pull request #1046 from oli-obk/unify_span_lint_usage
[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;
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
11 /// **What it does:** This lints about type with a `fn new() -> Self` method
12 /// and no implementation of
13 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
14 ///
15 /// **Why is this bad?** User might expect to be able to use
16 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
17 /// as the type can be
18 /// 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:** This lints about type with a `fn new() -> Self` method
54 /// and no implementation of
55 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
56 ///
57 /// **Why is this bad?** User might expect to be able to use
58 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
59 /// as the type can be
60 /// 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 LateLintPass for NewWithoutDefault {
93     fn check_fn(&mut self, cx: &LateContext, kind: FnKind, decl: &hir::FnDecl, _: &hir::Block, span: Span, id: ast::NodeId) {
94         if in_external_macro(cx, span) {
95             return;
96         }
97
98         if let FnKind::Method(name, ref sig, _, _) = kind {
99             if sig.constness == hir::Constness::Const {
100                 // can't be implemented by default
101                 return;
102             }
103             if decl.inputs.is_empty() && name.as_str() == "new" && cx.access_levels.is_reachable(id) {
104                 let self_ty = cx.tcx
105                     .lookup_item_type(cx.tcx.map.local_def_id(cx.tcx.map.get_parent(id)))
106                     .ty;
107                 if_let_chain!{[
108                     self_ty.walk_shallow().next().is_none(), // implements_trait does not work with generics
109                     let Some(ret_ty) = return_ty(cx, id),
110                     same_tys(cx, self_ty, ret_ty, id),
111                     let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT),
112                     !implements_trait(cx, self_ty, default_trait_id, Vec::new())
113                 ], {
114                     if can_derive_default(self_ty, cx, default_trait_id) {
115                         span_lint_and_then(cx,
116                                            NEW_WITHOUT_DEFAULT_DERIVE, span,
117                                            &format!("you should consider deriving a \
118                                                      `Default` implementation for `{}`",
119                                                     self_ty),
120                                            |db| {
121                                                db.span_suggestion(span, "try this", "#[derive(Default)]".into());
122                                            });
123                     } else {
124                         span_lint_and_then(cx,
125                                            NEW_WITHOUT_DEFAULT, span,
126                                            &format!("you should consider adding a \
127                                                     `Default` implementation for `{}`",
128                                                     self_ty),
129                                            |db| {
130                                                db.span_suggestion(span,
131                                                                   "try this",
132                                                                   format!("impl Default for {} {{ fn default() -> \
133                                                                           Self {{ {}::new() }} }}", self_ty, self_ty));
134                                            });
135                     }
136                 }}
137             }
138         }
139     }
140 }
141
142 fn can_derive_default<'t, 'c>(ty: ty::Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> bool {
143     match ty.sty {
144         ty::TyStruct(ref adt_def, ref substs) => {
145             for field in adt_def.all_fields() {
146                 let f_ty = field.ty(cx.tcx, substs);
147                 if !implements_trait(cx, f_ty, default_trait_id, Vec::new()) {
148                     return false;
149                 }
150             }
151             true
152         }
153         _ => false,
154     }
155 }