Skip to content

Commit d71e030

Browse files
committed
Merge pull request #938 from Manishearth/fix-876
Split `new_without_default` and `new_without_default_derive`.
2 parents 84098f5 + 9cfc422 commit d71e030

File tree

6 files changed

+82
-15
lines changed

6 files changed

+82
-15
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ All notable changes to this project will be documented in this file.
174174
[`neg_multiply`]: https://github.com/Manishearth/rust-clippy/wiki#neg_multiply
175175
[`new_ret_no_self`]: https://github.com/Manishearth/rust-clippy/wiki#new_ret_no_self
176176
[`new_without_default`]: https://github.com/Manishearth/rust-clippy/wiki#new_without_default
177+
[`new_without_default_derive`]: https://github.com/Manishearth/rust-clippy/wiki#new_without_default_derive
177178
[`no_effect`]: https://github.com/Manishearth/rust-clippy/wiki#no_effect
178179
[`non_ascii_literal`]: https://github.com/Manishearth/rust-clippy/wiki#non_ascii_literal
179180
[`nonminimal_bool`]: https://github.com/Manishearth/rust-clippy/wiki#nonminimal_bool

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Table of contents:
1717

1818
## Lints
1919

20-
There are 150 lints included in this crate:
20+
There are 151 lints included in this crate:
2121

2222
name | default | meaning
2323
---------------------------------------------------------------------------------------------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -107,6 +107,7 @@ name
107107
[neg_multiply](https://github.com/Manishearth/rust-clippy/wiki#neg_multiply) | warn | Warns on multiplying integers with -1
108108
[new_ret_no_self](https://github.com/Manishearth/rust-clippy/wiki#new_ret_no_self) | warn | not returning `Self` in a `new` method
109109
[new_without_default](https://github.com/Manishearth/rust-clippy/wiki#new_without_default) | warn | `fn new() -> Self` method without `Default` implementation
110+
[new_without_default_derive](https://github.com/Manishearth/rust-clippy/wiki#new_without_default_derive) | warn | `fn new() -> Self` without `#[derive]`able `Default` implementation
110111
[no_effect](https://github.com/Manishearth/rust-clippy/wiki#no_effect) | warn | statements with no effect
111112
[non_ascii_literal](https://github.com/Manishearth/rust-clippy/wiki#non_ascii_literal) | allow | using any literal non-ASCII chars in a string literal; suggests using the \\u escape instead
112113
[nonminimal_bool](https://github.com/Manishearth/rust-clippy/wiki#nonminimal_bool) | allow | checks for boolean expressions that can be written more concisely

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,7 @@ pub fn plugin_registrar(reg: &mut Registry) {
527527
needless_update::NEEDLESS_UPDATE,
528528
neg_multiply::NEG_MULTIPLY,
529529
new_without_default::NEW_WITHOUT_DEFAULT,
530+
new_without_default::NEW_WITHOUT_DEFAULT_DERIVE,
530531
no_effect::NO_EFFECT,
531532
no_effect::UNNECESSARY_OPERATION,
532533
non_expressive_names::MANY_SINGLE_CHAR_NAMES,

src/new_without_default.rs

Lines changed: 74 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use rustc::hir::intravisit::FnKind;
2+
use rustc::hir::def_id::DefId;
23
use rustc::hir;
34
use rustc::lint::*;
5+
use rustc::ty;
46
use syntax::ast;
57
use syntax::codemap::Span;
68
use utils::paths;
@@ -20,41 +22,70 @@ use utils::{get_trait_def_id, implements_trait, in_external_macro, return_ty, sa
2022
/// **Example:**
2123
///
2224
/// ```rust,ignore
23-
/// struct Foo;
25+
/// struct Foo(Bar);
2426
///
2527
/// impl Foo {
2628
/// fn new() -> Self {
27-
/// Foo
29+
/// Foo(Bar::new())
2830
/// }
2931
/// }
3032
/// ```
3133
///
3234
/// Instead, use:
3335
///
3436
/// ```rust
35-
/// struct Foo;
37+
/// struct Foo(Bar);
3638
///
3739
/// impl Default for Foo {
3840
/// fn default() -> Self {
39-
/// Foo
41+
/// Foo(Bar::new())
4042
/// }
4143
/// }
4244
/// ```
4345
///
4446
/// You can also have `new()` call `Default::default()`
45-
///
4647
declare_lint! {
4748
pub NEW_WITHOUT_DEFAULT,
4849
Warn,
4950
"`fn new() -> Self` method without `Default` implementation"
5051
}
5152

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+
5283
#[derive(Copy,Clone)]
5384
pub struct NewWithoutDefault;
5485

5586
impl LintPass for NewWithoutDefault {
5687
fn get_lints(&self) -> LintArray {
57-
lint_array!(NEW_WITHOUT_DEFAULT)
88+
lint_array!(NEW_WITHOUT_DEFAULT, NEW_WITHOUT_DEFAULT_DERIVE)
5889
}
5990
}
6091

@@ -66,19 +97,52 @@ impl LateLintPass for NewWithoutDefault {
6697

6798
if let FnKind::Method(name, _, _, _) = kind {
6899
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-
100+
let self_ty = cx.tcx.lookup_item_type(cx.tcx.map.local_def_id(
101+
cx.tcx.map.get_parent(id))).ty;
71102
if_let_chain!{[
72103
self_ty.walk_shallow().next().is_none(), // implements_trait does not work with generics
73104
let Some(ret_ty) = return_ty(cx, id),
74105
same_tys(cx, self_ty, ret_ty, id),
75106
let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT),
76107
!implements_trait(cx, self_ty, default_trait_id, Vec::new())
77108
], {
78-
span_lint(cx, NEW_WITHOUT_DEFAULT, span,
79-
&format!("you should consider adding a `Default` implementation for `{}`", self_ty));
109+
if can_derive_default(self_ty, cx, default_trait_id) {
110+
span_lint(cx,
111+
NEW_WITHOUT_DEFAULT_DERIVE, span,
112+
&format!("you should consider deriving a \
113+
`Default` implementation for `{}`",
114+
self_ty)).
115+
span_suggestion(span,
116+
"try this",
117+
"#[derive(Default)]".into());
118+
} else {
119+
span_lint(cx,
120+
NEW_WITHOUT_DEFAULT, span,
121+
&format!("you should consider adding a \
122+
`Default` implementation for `{}`",
123+
self_ty)).
124+
span_suggestion(span,
125+
"try this",
126+
format!("impl Default for {} {{ fn default() -> \
127+
Self {{ {}::new() }} }}", self_ty, self_ty));
128+
}
80129
}}
81130
}
82131
}
83132
}
84133
}
134+
135+
fn can_derive_default<'t, 'c>(ty: ty::Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> bool {
136+
match ty.sty {
137+
ty::TyStruct(ref adt_def, ref substs) => {
138+
for field in adt_def.all_fields() {
139+
let f_ty = field.ty(cx.tcx, substs);
140+
if !implements_trait(cx, f_ty, default_trait_id, Vec::new()) {
141+
return false
142+
}
143+
}
144+
true
145+
},
146+
_ => false
147+
}
148+
}

tests/compile-fail/methods.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
#![plugin(clippy)]
44

55
#![deny(clippy, clippy_pedantic)]
6-
#![allow(blacklisted_name, unused, print_stdout, non_ascii_literal, new_without_default)]
6+
#![allow(blacklisted_name, unused, print_stdout, non_ascii_literal, new_without_default, new_without_default_derive)]
77

88
use std::collections::BTreeMap;
99
use std::collections::HashMap;

tests/compile-fail/new_without_default.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@
22
#![plugin(clippy)]
33

44
#![allow(dead_code)]
5-
#![deny(new_without_default)]
5+
#![deny(new_without_default, new_without_default_derive)]
66

77
struct Foo;
88

99
impl Foo {
10-
fn new() -> Foo { Foo } //~ERROR: you should consider adding a `Default` implementation for `Foo`
10+
fn new() -> Foo { Foo } //~ERROR: you should consider deriving a `Default` implementation for `Foo`
1111
}
1212

1313
struct Bar;
1414

1515
impl Bar {
16-
fn new() -> Self { Bar } //~ERROR: you should consider adding a `Default` implementation for `Bar`
16+
fn new() -> Self { Bar } //~ERROR: you should consider deriving a `Default` implementation for `Bar`
1717
}
1818

1919
struct Ok;

0 commit comments

Comments
 (0)