Skip to content

Commit 021712b

Browse files
authored
Implement lint unconstructible_pub_struct
1 parent 5e33838 commit 021712b

File tree

7 files changed

+297
-24
lines changed

7 files changed

+297
-24
lines changed

compiler/rustc_lint_defs/src/builtin.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ declare_lint_pass! {
110110
TYVAR_BEHIND_RAW_POINTER,
111111
UNCONDITIONAL_PANIC,
112112
UNCONDITIONAL_RECURSION,
113+
UNCONSTRUCTIBLE_PUB_STRUCT,
113114
UNCOVERED_PARAM_IN_PROJECTION,
114115
UNEXPECTED_CFGS,
115116
UNFULFILLED_LINT_EXPECTATIONS,
@@ -755,6 +756,38 @@ declare_lint! {
755756
"detect unused, unexported items"
756757
}
757758

759+
declare_lint! {
760+
/// The `unconstructible_pub_struct` lint detects public structs that
761+
/// are unused locally and cannot be constructed externally.
762+
///
763+
/// ### Example
764+
///
765+
/// ```rust,compile_fail
766+
/// #![deny(unconstructible_pub_struct)]
767+
///
768+
/// pub struct Foo(i32);
769+
/// # fn main() {}
770+
/// ```
771+
///
772+
/// {{produces}}
773+
///
774+
/// ### Explanation
775+
///
776+
/// Unconstructible pub structs may signal a mistake or unfinished code.
777+
/// To silence the warning for individual items, prefix the name with an
778+
/// underscore such as `_Foo`.
779+
///
780+
/// To preserve this lint, add a field with unit or never types that
781+
/// indicate that the behavior is intentional, or use `PhantomData` as
782+
/// field types if the struct is only used at the type level to check
783+
/// things like well-formedness.
784+
///
785+
/// Otherwise, consider removing it if the struct is no longer in use.
786+
pub UNCONSTRUCTIBLE_PUB_STRUCT,
787+
Allow,
788+
"detects pub structs that are unused locally and cannot be constructed externally"
789+
}
790+
758791
declare_lint! {
759792
/// The `unused_attributes` lint detects attributes that were not used by
760793
/// the compiler.

compiler/rustc_middle/src/query/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1205,6 +1205,7 @@ rustc_queries! {
12051205
query live_symbols_and_ignored_derived_traits(_: ()) -> &'tcx (
12061206
LocalDefIdSet,
12071207
LocalDefIdMap<FxIndexSet<DefId>>,
1208+
LocalDefIdSet,
12081209
) {
12091210
arena_cache
12101211
desc { "finding live symbols in crate" }

compiler/rustc_passes/messages.ftl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,10 @@ passes_trait_impl_const_stable =
590590
passes_transparent_incompatible =
591591
transparent {$target} cannot have other repr hints
592592
593+
passes_unconstructible_pub_struct =
594+
pub struct `{$name}` is unconstructible externally and never constructed locally
595+
.help = this struct may be unused locally and also externally, consider removing it
596+
593597
passes_unexportable_adt_with_private_fields = ADT types with private fields are not exportable
594598
.note = `{$field_name}` is private
595599

compiler/rustc_passes/src/dead.rs

Lines changed: 137 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use hir::def_id::{LocalDefIdMap, LocalDefIdSet};
99
use rustc_abi::FieldIdx;
1010
use rustc_data_structures::fx::FxIndexSet;
1111
use rustc_errors::MultiSpan;
12-
use rustc_hir::def::{CtorOf, DefKind, Res};
12+
use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
1313
use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
1414
use rustc_hir::intravisit::{self, Visitor};
1515
use rustc_hir::{self as hir, Node, PatKind, QPath};
@@ -18,12 +18,13 @@ use rustc_middle::middle::privacy::Level;
1818
use rustc_middle::query::Providers;
1919
use rustc_middle::ty::{self, AssocTag, TyCtxt};
2020
use rustc_middle::{bug, span_bug};
21-
use rustc_session::lint::builtin::DEAD_CODE;
21+
use rustc_session::lint::builtin::{DEAD_CODE, UNCONSTRUCTIBLE_PUB_STRUCT};
2222
use rustc_session::lint::{self, LintExpectationId};
2323
use rustc_span::{Symbol, kw, sym};
2424

2525
use crate::errors::{
26-
ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment,
26+
ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UnconstructiblePubStruct,
27+
UselessAssignment,
2728
};
2829

2930
/// Any local definition that may call something in its body block should be explored. For example,
@@ -66,6 +67,38 @@ fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
6667
}
6768
}
6869

70+
fn struct_can_be_constructed_directly(tcx: TyCtxt<'_>, id: LocalDefId) -> bool {
71+
let adt_def = tcx.adt_def(id);
72+
73+
// Skip types contain fields of unit and never type,
74+
// it's usually intentional to make the type not constructible
75+
if adt_def.all_fields().any(|field| {
76+
let field_type = tcx.type_of(field.did).instantiate_identity();
77+
field_type.is_unit() || field_type.is_never()
78+
}) {
79+
return true;
80+
}
81+
82+
return adt_def.all_fields().all(|field| {
83+
let field_type = tcx.type_of(field.did).instantiate_identity();
84+
// Skip fields of PhantomData,
85+
// cause it's a common way to check things like well-formedness
86+
if field_type.is_phantom_data() {
87+
return true;
88+
}
89+
90+
field.vis.is_public()
91+
});
92+
}
93+
94+
fn method_has_no_receiver(tcx: TyCtxt<'_>, id: LocalDefId) -> bool {
95+
if let Some(fn_decl) = tcx.hir_fn_decl_by_hir_id(tcx.local_def_id_to_hir_id(id)) {
96+
!fn_decl.implicit_self.has_implicit_self()
97+
} else {
98+
true
99+
}
100+
}
101+
69102
/// Determine if a work from the worklist is coming from a `#[allow]`
70103
/// or a `#[expect]` of `dead_code`
71104
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
@@ -370,6 +403,28 @@ impl<'tcx> MarkSymbolVisitor<'tcx> {
370403
}
371404
}
372405

406+
fn mark_live_symbols_until_unsolved_items_fixed(
407+
&mut self,
408+
unsolved_items: &mut Vec<LocalDefId>,
409+
) {
410+
self.mark_live_symbols();
411+
412+
// We have marked the primary seeds as live. We now need to process unsolved items from traits
413+
// and trait impls: add them to the work list if the trait or the implemented type is live.
414+
let mut items_to_check: Vec<_> = unsolved_items
415+
.extract_if(.., |&mut local_def_id| self.check_impl_or_impl_item_live(local_def_id))
416+
.collect();
417+
418+
while !items_to_check.is_empty() {
419+
self.worklist.extend(items_to_check.drain(..).map(|id| (id, ComesFromAllowExpect::No)));
420+
self.mark_live_symbols();
421+
422+
items_to_check.extend(unsolved_items.extract_if(.., |&mut local_def_id| {
423+
self.check_impl_or_impl_item_live(local_def_id)
424+
}));
425+
}
426+
}
427+
373428
/// Automatically generated items marked with `rustc_trivial_field_reads`
374429
/// will be ignored for the purposes of dead code analysis (see PR #85200
375430
/// for discussion).
@@ -492,7 +547,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> {
492547
.and_then(|def_id| def_id.as_local()),
493548
),
494549
// impl items are live if the corresponding traits are live
495-
DefKind::Impl { of_trait: true } => (
550+
DefKind::Impl { .. } => (
496551
local_def_id,
497552
self.tcx
498553
.impl_trait_ref(local_def_id)
@@ -684,6 +739,12 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
684739
}
685740
}
686741

742+
fn has_allow_unconstructible_pub_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
743+
let hir_id = tcx.local_def_id_to_hir_id(def_id);
744+
let lint_level = tcx.lint_level_at_node(UNCONSTRUCTIBLE_PUB_STRUCT, hir_id).level;
745+
matches!(lint_level, lint::Allow | lint::Expect)
746+
}
747+
687748
fn has_allow_dead_code_or_lang_attr(
688749
tcx: TyCtxt<'_>,
689750
def_id: LocalDefId,
@@ -743,7 +804,9 @@ fn maybe_record_as_seed<'tcx>(
743804
unsolved_items: &mut Vec<LocalDefId>,
744805
) {
745806
let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id);
746-
if let Some(comes_from_allow) = allow_dead_code {
807+
if let Some(comes_from_allow) = allow_dead_code
808+
&& !tcx.effective_visibilities(()).is_reachable(owner_id.def_id)
809+
{
747810
worklist.push((owner_id.def_id, comes_from_allow));
748811
}
749812

@@ -807,6 +870,33 @@ fn create_and_seed_worklist(
807870
effective_vis
808871
.is_public_at_level(Level::Reachable)
809872
.then_some(id)
873+
.filter(|id| {
874+
let (is_seed, is_impl_or_impl_item) = match tcx.def_kind(*id) {
875+
DefKind::Impl { .. } => (false, true),
876+
DefKind::AssocFn => (
877+
!matches!(tcx.def_kind(tcx.local_parent(*id)), DefKind::Impl { .. })
878+
|| method_has_no_receiver(tcx, *id),
879+
true,
880+
),
881+
DefKind::Struct => (
882+
has_allow_unconstructible_pub_struct(tcx, *id)
883+
|| struct_can_be_constructed_directly(tcx, *id),
884+
false,
885+
),
886+
DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => (
887+
has_allow_unconstructible_pub_struct(tcx, tcx.local_parent(*id))
888+
|| struct_can_be_constructed_directly(tcx, tcx.local_parent(*id)),
889+
false,
890+
),
891+
_ => (true, false),
892+
};
893+
894+
if !is_seed && is_impl_or_impl_item {
895+
unsolved_impl_item.push(*id);
896+
}
897+
898+
is_seed
899+
})
810900
.map(|id| (id, ComesFromAllowExpect::No))
811901
})
812902
// Seed entry point
@@ -827,7 +917,7 @@ fn create_and_seed_worklist(
827917
fn live_symbols_and_ignored_derived_traits(
828918
tcx: TyCtxt<'_>,
829919
(): (),
830-
) -> (LocalDefIdSet, LocalDefIdMap<FxIndexSet<DefId>>) {
920+
) -> (LocalDefIdSet, LocalDefIdMap<FxIndexSet<DefId>>, LocalDefIdSet) {
831921
let (worklist, mut unsolved_items) = create_and_seed_worklist(tcx);
832922
let mut symbol_visitor = MarkSymbolVisitor {
833923
worklist,
@@ -841,28 +931,29 @@ fn live_symbols_and_ignored_derived_traits(
841931
ignore_variant_stack: vec![],
842932
ignored_derived_traits: Default::default(),
843933
};
844-
symbol_visitor.mark_live_symbols();
934+
symbol_visitor.mark_live_symbols_until_unsolved_items_fixed(&mut unsolved_items);
845935

846-
// We have marked the primary seeds as live. We now need to process unsolved items from traits
847-
// and trait impls: add them to the work list if the trait or the implemented type is live.
848-
let mut items_to_check: Vec<_> = unsolved_items
849-
.extract_if(.., |&mut local_def_id| {
850-
symbol_visitor.check_impl_or_impl_item_live(local_def_id)
851-
})
852-
.collect();
936+
let reachable_items =
937+
tcx.effective_visibilities(()).iter().filter_map(|(&id, effective_vis)| {
938+
effective_vis.is_public_at_level(Level::Reachable).then_some(id)
939+
});
853940

854-
while !items_to_check.is_empty() {
855-
symbol_visitor
856-
.worklist
857-
.extend(items_to_check.drain(..).map(|id| (id, ComesFromAllowExpect::No)));
858-
symbol_visitor.mark_live_symbols();
941+
let mut unstructurable_pub_structs = LocalDefIdSet::default();
942+
for id in reachable_items {
943+
if symbol_visitor.live_symbols.contains(&id) {
944+
continue;
945+
}
946+
947+
if matches!(tcx.def_kind(id), DefKind::Struct) {
948+
unstructurable_pub_structs.insert(id);
949+
}
859950

860-
items_to_check.extend(unsolved_items.extract_if(.., |&mut local_def_id| {
861-
symbol_visitor.check_impl_or_impl_item_live(local_def_id)
862-
}));
951+
symbol_visitor.worklist.push((id, ComesFromAllowExpect::No));
863952
}
864953

865-
(symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
954+
symbol_visitor.mark_live_symbols_until_unsolved_items_fixed(&mut unsolved_items);
955+
956+
(symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits, unstructurable_pub_structs)
866957
}
867958

868959
struct DeadItem {
@@ -1142,7 +1233,8 @@ impl<'tcx> DeadVisitor<'tcx> {
11421233
}
11431234

11441235
fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) {
1145-
let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(());
1236+
let (live_symbols, ignored_derived_traits, unstructurable_pub_structs) =
1237+
tcx.live_symbols_and_ignored_derived_traits(());
11461238
let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
11471239

11481240
let module_items = tcx.hir_module_items(module);
@@ -1229,6 +1321,27 @@ fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) {
12291321
for foreign_item in module_items.foreign_items() {
12301322
visitor.check_definition(foreign_item.owner_id.def_id);
12311323
}
1324+
1325+
for item in module_items.free_items() {
1326+
let def_id = item.owner_id.def_id;
1327+
1328+
if !unstructurable_pub_structs.contains(&def_id) {
1329+
continue;
1330+
}
1331+
1332+
let Some(name) = tcx.opt_item_name(def_id.to_def_id()) else {
1333+
continue;
1334+
};
1335+
1336+
if name.as_str().starts_with('_') {
1337+
continue;
1338+
}
1339+
1340+
let hir_id = tcx.local_def_id_to_hir_id(def_id);
1341+
let vis_span = tcx.hir_node(hir_id).expect_item().vis_span;
1342+
let diag = UnconstructiblePubStruct { name, vis_span };
1343+
tcx.emit_node_span_lint(UNCONSTRUCTIBLE_PUB_STRUCT, hir_id, tcx.hir_span(hir_id), diag);
1344+
}
12321345
}
12331346

12341347
pub(crate) fn provide(providers: &mut Providers) {

compiler/rustc_passes/src/errors.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1268,6 +1268,14 @@ pub(crate) enum MultipleDeadCodes<'tcx> {
12681268
},
12691269
}
12701270

1271+
#[derive(LintDiagnostic)]
1272+
#[diag(passes_unconstructible_pub_struct)]
1273+
pub(crate) struct UnconstructiblePubStruct {
1274+
pub name: Symbol,
1275+
#[help]
1276+
pub vis_span: Span,
1277+
}
1278+
12711279
#[derive(Subdiagnostic)]
12721280
#[note(passes_enum_variant_same_name)]
12731281
pub(crate) struct EnumVariantSameName<'tcx> {

0 commit comments

Comments
 (0)