exhaustive_structs: don't trigger for structs with private fields

This commit is contained in:
Manish Goregaokar 2021-02-01 18:38:43 -08:00
parent c5f3f9df3b
commit 0fb09d6b21
4 changed files with 42 additions and 20 deletions

View File

@ -75,10 +75,14 @@ impl LateLintPass<'_> for ExhaustiveItems {
if cx.access_levels.is_exported(item.hir_id);
if !item.attrs.iter().any(|a| a.has_name(sym::non_exhaustive));
then {
let (lint, msg) = if let ItemKind::Enum(..) = item.kind {
(EXHAUSTIVE_ENUMS, "exported enums should not be exhaustive")
} else {
let (lint, msg) = if let ItemKind::Struct(ref v, ..) = item.kind {
if v.fields().iter().any(|f| !f.vis.node.is_pub()) {
// skip structs with private fields
return;
}
(EXHAUSTIVE_STRUCTS, "exported structs should not be exhaustive")
} else {
(EXHAUSTIVE_ENUMS, "exported enums should not be exhaustive")
};
let suggestion_span = item.span.shrink_to_lo();
let indent = " ".repeat(indent_of(cx, item.span).unwrap_or(0));

View File

@ -56,27 +56,36 @@ pub mod enums {
pub mod structs {
#[non_exhaustive]
pub struct Exhaustive {
foo: u8,
bar: String,
pub foo: u8,
pub bar: String,
}
// no warning, already non_exhaustive
#[non_exhaustive]
pub struct NonExhaustive {
foo: u8,
bar: String,
pub foo: u8,
pub bar: String,
}
// no warning, private fields
pub struct ExhaustivePrivateFieldTuple(u8);
// no warning, private fields
pub struct ExhaustivePrivateField {
pub foo: u8,
bar: String
}
// no warning, private
struct ExhaustivePrivate {
foo: u8,
bar: String,
pub foo: u8,
pub bar: String,
}
// no warning, private
#[non_exhaustive]
struct NonExhaustivePrivate {
foo: u8,
bar: String,
pub foo: u8,
pub bar: String,
}
}

View File

@ -53,27 +53,36 @@ pub mod enums {
pub mod structs {
pub struct Exhaustive {
foo: u8,
bar: String,
pub foo: u8,
pub bar: String,
}
// no warning, already non_exhaustive
#[non_exhaustive]
pub struct NonExhaustive {
foo: u8,
pub foo: u8,
pub bar: String,
}
// no warning, private fields
pub struct ExhaustivePrivateFieldTuple(u8);
// no warning, private fields
pub struct ExhaustivePrivateField {
pub foo: u8,
bar: String,
}
// no warning, private
struct ExhaustivePrivate {
foo: u8,
bar: String,
pub foo: u8,
pub bar: String,
}
// no warning, private
#[non_exhaustive]
struct NonExhaustivePrivate {
foo: u8,
bar: String,
pub foo: u8,
pub bar: String,
}
}

View File

@ -41,8 +41,8 @@ error: exported structs should not be exhaustive
--> $DIR/exhaustive_items.rs:55:5
|
LL | / pub struct Exhaustive {
LL | | foo: u8,
LL | | bar: String,
LL | | pub foo: u8,
LL | | pub bar: String,
LL | | }
| |_____^
|