Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make needless_update ignore non_exhaustive structs #6464

Merged
merged 2 commits into from
Dec 19, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions clippy_lints/src/needless_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,14 @@ declare_clippy_lint! {
/// # z: i32,
/// # }
/// # let zero_point = Point { x: 0, y: 0, z: 0 };
///
/// #
/// # #[non_exhaustive]
ahouts marked this conversation as resolved.
Show resolved Hide resolved
/// # struct Options {
/// # a: bool,
/// # b: i32,
/// # }
/// # let default_options = Options { a: false, b: 0 };
/// #
/// // Bad
/// Point {
/// x: 1,
Expand All @@ -36,6 +43,14 @@ declare_clippy_lint! {
/// y: 1,
/// ..zero_point
/// };
///
/// // this lint is not applied to structs marked with [non_exhaustive](https://doc.rust-lang.org/reference/attributes/type_system.html)
/// // Ok
/// Options {
/// a: true,
/// b: 321,
/// ..default_options
/// };
/// ```
pub NEEDLESS_UPDATE,
complexity,
Expand All @@ -49,7 +64,9 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessUpdate {
if let ExprKind::Struct(_, ref fields, Some(ref base)) = expr.kind {
let ty = cx.typeck_results().expr_ty(expr);
if let ty::Adt(def, _) = ty.kind() {
if fields.len() == def.non_enum_variant().fields.len() {
if fields.len() == def.non_enum_variant().fields.len()
&& !def.variants[0_usize.into()].is_field_list_non_exhaustive()
{
span_lint(
cx,
NEEDLESS_UPDATE,
Expand Down
11 changes: 11 additions & 0 deletions tests/ui/needless_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,20 @@ struct S {
pub b: i32,
}

#[non_exhaustive]
struct T {
pub x: i32,
pub y: i32,
}

fn main() {
let base = S { a: 0, b: 0 };
S { ..base }; // no error
S { a: 1, ..base }; // no error
S { a: 1, b: 1, ..base };

let base = T { x: 0, y: 0 };
T { ..base }; // no error
T { x: 1, ..base }; // no error
T { x: 1, y: 1, ..base }; // no error
}
2 changes: 1 addition & 1 deletion tests/ui/needless_update.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: struct update has no effect, all the fields in the struct have already been specified
--> $DIR/needless_update.rs:13:23
--> $DIR/needless_update.rs:19:23
|
LL | S { a: 1, b: 1, ..base };
| ^^^^
Expand Down