1 use rustc::hir::intravisit::FnKind;
5 use syntax::codemap::Span;
7 use utils::{get_trait_def_id, implements_trait, in_external_macro, return_ty, same_tys, span_lint};
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)
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.
18 /// **Known problems:** Hopefully none.
26 /// fn new() -> Self {
37 /// impl Default for Foo {
38 /// fn default() -> Self {
44 /// You can also have `new()` call `Default::default()`
47 pub NEW_WITHOUT_DEFAULT,
49 "`fn new() -> Self` method without `Default` implementation"
53 pub struct NewWithoutDefault;
55 impl LintPass for NewWithoutDefault {
56 fn get_lints(&self) -> LintArray {
57 lint_array!(NEW_WITHOUT_DEFAULT)
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) {
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;
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())
78 span_lint(cx, NEW_WITHOUT_DEFAULT, span,
79 &format!("you should consider adding a `Default` implementation for `{}`", self_ty));