Skip to content

Commit

Permalink
changes after review
Browse files Browse the repository at this point in the history
  • Loading branch information
FoseFx committed Mar 28, 2022
1 parent 5b8fc45 commit a3ed806
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 11 deletions.
21 changes: 10 additions & 11 deletions clippy_lints/src/unit_like_struct_brackets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ declare_clippy_lint! {
/// ```rust
/// struct Cookie;
/// ```
#[clippy::version = "1.61.0"]
#[clippy::version = "1.62.0"]
pub UNIT_LIKE_STRUCT_BRACKETS,
style,
"finds struct declarations with empty brackets"
Expand All @@ -32,7 +32,9 @@ impl EarlyLintPass for UnitLikeStructBrackets {
fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
let span_after_ident = item.span.with_lo(item.ident.span.hi());

if let ItemKind::Struct(var_data, _) = &item.kind && has_no_fields(cx, var_data, span_after_ident) {
if let ItemKind::Struct(var_data, _) = &item.kind
&& !is_unit_like_struct(var_data)
&& has_no_fields(cx, var_data, span_after_ident) {
span_lint_and_then(
cx,
UNIT_LIKE_STRUCT_BRACKETS,
Expand All @@ -50,23 +52,20 @@ impl EarlyLintPass for UnitLikeStructBrackets {
}
}

fn has_fields_in_hir(var_data: &VariantData) -> bool {
match var_data {
VariantData::Struct(defs, _) | VariantData::Tuple(defs, _) => !defs.is_empty(),
VariantData::Unit(_) => true,
}
}

fn has_no_ident_token(braces_span_str: &str) -> bool {
!rustc_lexer::tokenize(braces_span_str).any(|t| t.kind == TokenKind::Ident)
}

fn is_unit_like_struct(var_data: &VariantData) -> bool {
matches!(var_data, VariantData::Unit(_))
}

fn has_no_fields(cx: &EarlyContext<'_>, var_data: &VariantData, braces_span: Span) -> bool {
if has_fields_in_hir(var_data) {
if !var_data.fields().is_empty() {
return false;
}

// there might still be field declarations hidden from HIR
// there might still be field declarations hidden from the AST
// (conditionaly compiled code using #[cfg(..)])

let Some(braces_span_str) = snippet_opt(cx, braces_span) else {
Expand Down
2 changes: 2 additions & 0 deletions tests/ui/unit_like_struct_brackets.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,7 @@ struct MyStruct {
field: u8,
}
struct MyTupleStruct(usize, String); // should not trigger lint
struct MySingleTupleStruct(usize); // should not trigger lint
struct MyUnitLikeStruct; // should not trigger lint

fn main() {}
2 changes: 2 additions & 0 deletions tests/ui/unit_like_struct_brackets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,7 @@ struct MyStruct {
field: u8,
}
struct MyTupleStruct(usize, String); // should not trigger lint
struct MySingleTupleStruct(usize); // should not trigger lint
struct MyUnitLikeStruct; // should not trigger lint

fn main() {}

0 comments on commit a3ed806

Please sign in to comment.