]> git.lizzy.rs Git - rust.git/blob - src/new_without_default.rs
46021ec883678909c7fb56f3233c8cab7909333d
[rust.git] / src / new_without_default.rs
1 use rustc::hir::intravisit::FnKind;
2 use rustc::hir;
3 use rustc::lint::*;
4 use syntax::ast;
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};
8
9 /// **What it does:** This lints about type with a `fn new() -> Self` method
10 /// and no implementation of
11 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
12 ///
13 /// **Why is this bad?** User might expect to be able to use
14 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
15 /// as the type can be
16 /// constructed without arguments.
17 ///
18 /// **Known problems:** Hopefully none.
19 ///
20 /// **Example:**
21 ///
22 /// ```rust,ignore
23 /// struct Foo;
24 ///
25 /// impl Foo {
26 ///     fn new() -> Self {
27 ///         Foo
28 ///     }
29 /// }
30 /// ```
31 ///
32 /// Instead, use:
33 ///
34 /// ```rust
35 /// struct Foo;
36 ///
37 /// impl Default for Foo {
38 ///     fn default() -> Self {
39 ///         Foo
40 ///     }
41 /// }
42 /// ```
43 ///
44 /// You can also have `new()` call `Default::default()`
45 ///
46 declare_lint! {
47     pub NEW_WITHOUT_DEFAULT,
48     Warn,
49     "`fn new() -> Self` method without `Default` implementation"
50 }
51
52 #[derive(Copy,Clone)]
53 pub struct NewWithoutDefault;
54
55 impl LintPass for NewWithoutDefault {
56     fn get_lints(&self) -> LintArray {
57         lint_array!(NEW_WITHOUT_DEFAULT)
58     }
59 }
60
61 impl LateLintPass for NewWithoutDefault {
62     fn check_fn(&mut self, cx: &LateContext, kind: FnKind, decl: &hir::FnDecl, _: &hir::Block, span: Span, id: ast::NodeId) {
63         if in_external_macro(cx, span) {
64             return;
65         }
66
67         if let FnKind::Method(name, _, _, _) = kind {
68             if decl.inputs.is_empty() && name.as_str() == "new" {
69                 let self_ty = cx.tcx.lookup_item_type(cx.tcx.map.local_def_id(cx.tcx.map.get_parent(id))).ty;
70
71                 if_let_chain!{[
72                     self_ty.walk_shallow().next().is_none(), // implements_trait does not work with generics
73                     let Some(ret_ty) = return_ty(cx, id),
74                     same_tys(cx, self_ty, ret_ty, id),
75                     let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT),
76                     !implements_trait(cx, self_ty, default_trait_id, Vec::new())
77                 ], {
78                     span_lint(cx, NEW_WITHOUT_DEFAULT, span,
79                               &format!("you should consider adding a `Default` implementation for `{}`", self_ty));
80                 }}
81             }
82         }
83     }
84 }