Skip to content

Commit 1eb7608

Browse files
committed
make needless_update ignore non_exhaustive structs
1 parent 5c00931 commit 1eb7608

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

clippy_lints/src/needless_update.rs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,14 @@ declare_clippy_lint! {
2121
/// # z: i32,
2222
/// # }
2323
/// # let zero_point = Point { x: 0, y: 0, z: 0 };
24-
///
24+
/// #
25+
/// # #[non_exhaustive]
26+
/// # struct Options {
27+
/// # a: bool,
28+
/// # b: i32,
29+
/// # }
30+
/// # let default_options = Options { a: false, b: 0 };
31+
/// #
2532
/// // Bad
2633
/// Point {
2734
/// x: 1,
@@ -36,6 +43,14 @@ declare_clippy_lint! {
3643
/// y: 1,
3744
/// ..zero_point
3845
/// };
46+
///
47+
/// // this lint is not applied to structs marked with [non_exhaustive](https://doc.rust-lang.org/reference/attributes/type_system.html)
48+
/// // Ok
49+
/// Options {
50+
/// a: true,
51+
/// b: 321,
52+
/// ..default_options
53+
/// };
3954
/// ```
4055
pub NEEDLESS_UPDATE,
4156
complexity,
@@ -49,7 +64,9 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessUpdate {
4964
if let ExprKind::Struct(_, ref fields, Some(ref base)) = expr.kind {
5065
let ty = cx.typeck_results().expr_ty(expr);
5166
if let ty::Adt(def, _) = ty.kind() {
52-
if fields.len() == def.non_enum_variant().fields.len() {
67+
if fields.len() == def.non_enum_variant().fields.len()
68+
&& !def.variants[0_usize.into()].is_field_list_non_exhaustive()
69+
{
5370
span_lint(
5471
cx,
5572
NEEDLESS_UPDATE,

tests/ui/needless_update.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,20 @@ struct S {
66
pub b: i32,
77
}
88

9+
#[non_exhaustive]
10+
struct T {
11+
pub x: i32,
12+
pub y: i32,
13+
}
14+
915
fn main() {
1016
let base = S { a: 0, b: 0 };
1117
S { ..base }; // no error
1218
S { a: 1, ..base }; // no error
1319
S { a: 1, b: 1, ..base };
20+
21+
let base = T { x: 0, y: 0 };
22+
T { ..base }; // no error
23+
T { x: 1, ..base }; // no error
24+
T { x: 1, y: 1, ..base }; // no error
1425
}

tests/ui/needless_update.stderr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: struct update has no effect, all the fields in the struct have already been specified
2-
--> $DIR/needless_update.rs:13:23
2+
--> $DIR/needless_update.rs:19:23
33
|
44
LL | S { a: 1, b: 1, ..base };
55
| ^^^^

0 commit comments

Comments
 (0)