Skip to content

Commit 2e2b3b3

Browse files
committed
Don't warn on pub fields of pub(restricted) structs
1 parent a83cf56 commit 2e2b3b3

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

compiler/rustc_lint/src/builtin.rs

+18-2
Original file line numberDiff line numberDiff line change
@@ -1424,8 +1424,24 @@ impl<'tcx> LateLintPass<'tcx> for UnreachablePub {
14241424
}
14251425

14261426
fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) {
1427-
if matches!(cx.tcx.parent_hir_node(field.hir_id), Node::Variant(_)) {
1428-
return;
1427+
match cx.tcx.parent_hir_node(field.hir_id) {
1428+
Node::Variant(_) => return,
1429+
// We don't want to lint on struct/union fields whose parent def is
1430+
// not public. We therefore check if the parent is a struct/union and
1431+
// if it `pub` we ignore the field.
1432+
//
1433+
// ```
1434+
// pub(crate) struct Hydrogen {
1435+
// pub neutrons: usize, // should not lint
1436+
// }
1437+
// ```
1438+
Node::Item(item)
1439+
if item.is_struct_or_union()
1440+
&& !cx.tcx.visibility(item.owner_id.def_id).is_public() =>
1441+
{
1442+
return;
1443+
}
1444+
_ => {}
14291445
}
14301446
self.perform_lint(cx, "field", field.def_id, field.vis_span, false);
14311447
}

tests/ui/lint/unreachable_pub.rs

+4
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ mod private_mod {
1515
// (... but not more-restricted fields)
1616
pub(crate) electrons: usize
1717
}
18+
pub(crate) struct Hydrogen {
19+
pub neutrons: usize, // the visibility is clearly defined by the struct above
20+
// no need to cluter the field definition
21+
}
1822
impl Hydrogen {
1923
// impls, too
2024
pub fn count_neutrons(&self) -> usize { self.neutrons } //~ WARNING unreachable_pub

0 commit comments

Comments
 (0)