Skip to content

Commit

Permalink
Don't warn on pub fields of pub(restricted) structs
Browse files Browse the repository at this point in the history
  • Loading branch information
Urgau committed Jun 5, 2024
1 parent a83cf56 commit 2e2b3b3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
20 changes: 18 additions & 2 deletions compiler/rustc_lint/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1424,8 +1424,24 @@ impl<'tcx> LateLintPass<'tcx> for UnreachablePub {
}

fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) {
if matches!(cx.tcx.parent_hir_node(field.hir_id), Node::Variant(_)) {
return;
match cx.tcx.parent_hir_node(field.hir_id) {
Node::Variant(_) => return,
// We don't want to lint on struct/union fields whose parent def is
// not public. We therefore check if the parent is a struct/union and
// if it `pub` we ignore the field.
//
// ```
// pub(crate) struct Hydrogen {
// pub neutrons: usize, // should not lint
// }
// ```
Node::Item(item)
if item.is_struct_or_union()
&& !cx.tcx.visibility(item.owner_id.def_id).is_public() =>
{
return;
}
_ => {}
}
self.perform_lint(cx, "field", field.def_id, field.vis_span, false);
}
Expand Down
4 changes: 4 additions & 0 deletions tests/ui/lint/unreachable_pub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ mod private_mod {
// (... but not more-restricted fields)
pub(crate) electrons: usize
}
pub(crate) struct Hydrogen {
pub neutrons: usize, // the visibility is clearly defined by the struct above
// no need to cluter the field definition
}
impl Hydrogen {
// impls, too
pub fn count_neutrons(&self) -> usize { self.neutrons } //~ WARNING unreachable_pub
Expand Down

0 comments on commit 2e2b3b3

Please sign in to comment.