Skip to content

Commit c4a69d4

Browse files
committed
Bring back enum DepKind.
It was removed in #115920 to enable it being moved to `rustc_query_system`, a move that has recently been reversed. It's much simpler as an enum. Also: - Remove the overly complicated `Debug` impl for `DepKind`. - Remove the trivial `DepKind` associated constants (`NULL` et al.) - Add an assertion to ensure that the number of `DepKinds` fits within a `u16`. - Rename `DEP_KIND_VARIANTS` as `DEP_KIND_NUM_VARIANTS`, to make it clearer that it's a count, not a collection. - Use `stringify!` in one place to make the code clearer.
1 parent 90b994b commit c4a69d4

11 files changed

Lines changed: 59 additions & 96 deletions

File tree

compiler/rustc_incremental/src/assert_dep_graph.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,7 @@ use rustc_hir::attrs::AttributeKind;
4444
use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
4545
use rustc_hir::intravisit::{self, Visitor};
4646
use rustc_middle::bug;
47-
use rustc_middle::dep_graph::{
48-
DepGraphQuery, DepKind, DepNode, DepNodeFilter, EdgeFilter, dep_kinds,
49-
};
47+
use rustc_middle::dep_graph::{DepGraphQuery, DepKind, DepNode, DepNodeFilter, EdgeFilter};
5048
use rustc_middle::hir::nested_filter;
5149
use rustc_middle::ty::TyCtxt;
5250
use rustc_span::{Span, Symbol, sym};
@@ -117,7 +115,7 @@ impl<'tcx> IfThisChanged<'tcx> {
117115
None => DepNode::from_def_path_hash(
118116
self.tcx,
119117
def_path_hash,
120-
dep_kinds::opt_hir_owner_nodes,
118+
DepKind::opt_hir_owner_nodes,
121119
),
122120
Some(n) => {
123121
match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) {

compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,8 @@ macro_rules! provide_one {
147147
// External query providers call `crate_hash` in order to register a dependency
148148
// on the crate metadata. The exception is `crate_hash` itself, which obviously
149149
// doesn't need to do this (and can't, as it would cause a query cycle).
150-
use rustc_middle::dep_graph::dep_kinds;
151-
if dep_kinds::$name != dep_kinds::crate_hash && $tcx.dep_graph.is_fully_enabled() {
150+
use rustc_middle::dep_graph::DepKind;
151+
if DepKind::$name != DepKind::crate_hash && $tcx.dep_graph.is_fully_enabled() {
152152
$tcx.ensure_ok().crate_hash($def_id.krate);
153153
}
154154

compiler/rustc_middle/src/dep_graph/dep_node.rs

Lines changed: 26 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -62,59 +62,34 @@ use crate::ich::StableHashingContext;
6262
use crate::mir::mono::MonoItem;
6363
use crate::ty::{TyCtxt, tls};
6464

65-
/// This serves as an index into arrays built by `make_dep_kind_array`.
66-
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
67-
pub struct DepKind {
68-
variant: u16,
69-
}
70-
65+
// `enum DepKind` is generated by `define_dep_nodes!` below.
7166
impl DepKind {
7267
#[inline]
73-
pub const fn new(variant: u16) -> Self {
74-
Self { variant }
68+
pub(crate) fn from_u16(u: u16) -> Self {
69+
if u > Self::MAX {
70+
panic!("Invalid DepKind {u}");
71+
}
72+
// SAFETY: See comment on DEP_KIND_NUM_VARIANTS
73+
unsafe { std::mem::transmute(u) }
7574
}
7675

7776
#[inline]
78-
pub const fn as_inner(&self) -> u16 {
79-
self.variant
77+
pub(crate) const fn as_u16(&self) -> u16 {
78+
*self as u16
8079
}
8180

8281
#[inline]
8382
pub const fn as_usize(&self) -> usize {
84-
self.variant as usize
83+
*self as usize
8584
}
8685

8786
pub(crate) fn name(self) -> &'static str {
8887
DEP_KIND_NAMES[self.as_usize()]
8988
}
9089

91-
/// We use this for most things when incr. comp. is turned off.
92-
pub(crate) const NULL: DepKind = dep_kinds::Null;
93-
94-
/// We use this to create a forever-red node.
95-
pub(crate) const RED: DepKind = dep_kinds::Red;
96-
97-
/// We use this to create a side effect node.
98-
pub(crate) const SIDE_EFFECT: DepKind = dep_kinds::SideEffect;
99-
100-
/// We use this to create the anon node with zero dependencies.
101-
pub(crate) const ANON_ZERO_DEPS: DepKind = dep_kinds::AnonZeroDeps;
102-
10390
/// This is the highest value a `DepKind` can have. It's used during encoding to
10491
/// pack information into the unused bits.
105-
pub(crate) const MAX: u16 = DEP_KIND_VARIANTS - 1;
106-
}
107-
108-
impl fmt::Debug for DepKind {
109-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110-
tls::with_opt(|opt_tcx| {
111-
if let Some(tcx) = opt_tcx {
112-
write!(f, "{}", tcx.dep_kind_vtable(*self).name)
113-
} else {
114-
f.debug_struct("DepKind").field("variant", &self.variant).finish()
115-
}
116-
})
117-
}
92+
pub(crate) const MAX: u16 = DEP_KIND_NUM_VARIANTS - 1;
11893
}
11994

12095
/// Combination of a [`DepKind`] and a key fingerprint that uniquely identifies
@@ -374,33 +349,26 @@ macro_rules! define_dep_nodes {
374349
// encoding. The derived Encodable/Decodable uses leb128 encoding which is
375350
// dense when only considering this enum. But DepKind is encoded in a larger
376351
// struct, and there we can take advantage of the unused bits in the u16.
352+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
377353
#[allow(non_camel_case_types)]
378-
#[repr(u16)] // Must be kept in sync with the inner type of `DepKind`.
379-
enum DepKindDefs {
354+
#[repr(u16)] // Must be kept in sync with the rest of `DepKind`.
355+
pub enum DepKind {
380356
$( $( #[$attr] )* $variant),*
381357
}
382358

383-
#[allow(non_upper_case_globals)]
384-
pub mod dep_kinds {
385-
use super::*;
386-
387-
$(
388-
// The `as u16` cast must be kept in sync with the inner type of `DepKind`.
389-
pub const $variant: DepKind = DepKind::new(DepKindDefs::$variant as u16);
390-
)*
391-
}
392-
393-
// This checks that the discriminants of the variants have been assigned consecutively
394-
// from 0 so that they can be used as a dense index.
395-
pub(crate) const DEP_KIND_VARIANTS: u16 = {
396-
let deps = &[$(dep_kinds::$variant,)*];
359+
// This computes the number of dep kind variants. Along the way, it sanity-checks that the
360+
// discriminants of the variants have been assigned consecutively from 0 so that they can
361+
// be used as a dense index, and that all discriminants fit in a `u16`.
362+
pub(crate) const DEP_KIND_NUM_VARIANTS: u16 = {
363+
let deps = &[$(DepKind::$variant,)*];
397364
let mut i = 0;
398365
while i < deps.len() {
399366
if i != deps[i].as_usize() {
400367
panic!();
401368
}
402369
i += 1;
403370
}
371+
assert!(deps.len() <= u16::MAX as usize);
404372
deps.len() as u16
405373
};
406374

@@ -412,7 +380,7 @@ macro_rules! define_dep_nodes {
412380

413381
pub(super) fn dep_kind_from_label_string(label: &str) -> Result<DepKind, ()> {
414382
match label {
415-
$( self::label_strs::$variant => Ok(self::dep_kinds::$variant), )*
383+
$( stringify!($variant) => Ok(self::DepKind::$variant), )*
416384
_ => Err(()),
417385
}
418386
}
@@ -433,7 +401,9 @@ rustc_with_all_queries!(define_dep_nodes![
433401
[] fn Null() -> (),
434402
/// We use this to create a forever-red node.
435403
[] fn Red() -> (),
404+
/// We use this to create a side effect node.
436405
[] fn SideEffect() -> (),
406+
/// We use this to create the anon node with zero dependencies.
437407
[] fn AnonZeroDeps() -> (),
438408
[] fn TraitSelect() -> (),
439409
[] fn CompileCodegenUnit() -> (),
@@ -444,7 +414,7 @@ rustc_with_all_queries!(define_dep_nodes![
444414
// WARNING: `construct` is generic and does not know that `CompileCodegenUnit` takes `Symbol`s as keys.
445415
// Be very careful changing this type signature!
446416
pub(crate) fn make_compile_codegen_unit(tcx: TyCtxt<'_>, name: Symbol) -> DepNode {
447-
DepNode::construct(tcx, dep_kinds::CompileCodegenUnit, &name)
417+
DepNode::construct(tcx, DepKind::CompileCodegenUnit, &name)
448418
}
449419

450420
// WARNING: `construct` is generic and does not know that `CompileMonoItem` takes `MonoItem`s as keys.
@@ -453,13 +423,13 @@ pub(crate) fn make_compile_mono_item<'tcx>(
453423
tcx: TyCtxt<'tcx>,
454424
mono_item: &MonoItem<'tcx>,
455425
) -> DepNode {
456-
DepNode::construct(tcx, dep_kinds::CompileMonoItem, mono_item)
426+
DepNode::construct(tcx, DepKind::CompileMonoItem, mono_item)
457427
}
458428

459429
// WARNING: `construct` is generic and does not know that `Metadata` takes `()`s as keys.
460430
// Be very careful changing this type signature!
461431
pub(crate) fn make_metadata(tcx: TyCtxt<'_>) -> DepNode {
462-
DepNode::construct(tcx, dep_kinds::Metadata, &())
432+
DepNode::construct(tcx, DepKind::Metadata, &())
463433
}
464434

465435
impl DepNode {

compiler/rustc_middle/src/dep_graph/graph.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ impl DepGraph {
142142

143143
// Instantiate a node with zero dependencies only once for anonymous queries.
144144
let _green_node_index = current.alloc_new_node(
145-
DepNode { kind: DepKind::ANON_ZERO_DEPS, key_fingerprint: current.anon_id_seed.into() },
145+
DepNode { kind: DepKind::AnonZeroDeps, key_fingerprint: current.anon_id_seed.into() },
146146
EdgesVec::new(),
147147
Fingerprint::ZERO,
148148
);
@@ -152,7 +152,7 @@ impl DepGraph {
152152
// Other nodes can use the always-red node as a fake dependency, to
153153
// ensure that their dependency list will never be all-green.
154154
let red_node_index = current.alloc_new_node(
155-
DepNode { kind: DepKind::RED, key_fingerprint: Fingerprint::ZERO.into() },
155+
DepNode { kind: DepKind::Red, key_fingerprint: Fingerprint::ZERO.into() },
156156
EdgesVec::new(),
157157
Fingerprint::ZERO,
158158
);
@@ -680,7 +680,7 @@ impl DepGraphData {
680680
// Use `send_new` so we get an unique index, even though the dep node is not.
681681
let dep_node_index = self.current.encoder.send_new(
682682
DepNode {
683-
kind: DepKind::SIDE_EFFECT,
683+
kind: DepKind::SideEffect,
684684
key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
685685
},
686686
Fingerprint::ZERO,
@@ -713,7 +713,7 @@ impl DepGraphData {
713713
prev_index,
714714
&self.colors,
715715
DepNode {
716-
kind: DepKind::SIDE_EFFECT,
716+
kind: DepKind::SideEffect,
717717
key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
718718
},
719719
Fingerprint::ZERO,

compiler/rustc_middle/src/dep_graph/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@ use std::panic;
33
use tracing::instrument;
44

55
pub use self::dep_node::{
6-
DepKind, DepKindVTable, DepNode, DepNodeKey, WorkProductId, dep_kind_from_label, dep_kinds,
7-
label_strs,
6+
DepKind, DepKindVTable, DepNode, DepNodeKey, WorkProductId, dep_kind_from_label, label_strs,
87
};
98
pub use self::graph::{
109
DepGraph, DepGraphData, DepNodeIndex, QuerySideEffect, TaskDepsRef, WorkProduct,

compiler/rustc_middle/src/dep_graph/serialized.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ const DEP_NODE_WIDTH_BITS: usize = DEP_NODE_SIZE / 2;
8484

8585
/// Data for use when recompiling the **current crate**.
8686
///
87-
/// There may be unused indices with DEP_KIND_NULL in this graph due to batch allocation of
87+
/// There may be unused indices with DepKind::Null in this graph due to batch allocation of
8888
/// indices to threads.
8989
#[derive(Debug, Default)]
9090
pub struct SerializedDepGraph {
@@ -220,7 +220,7 @@ impl SerializedDepGraph {
220220

221221
let mut nodes = IndexVec::from_elem_n(
222222
DepNode {
223-
kind: DepKind::NULL,
223+
kind: DepKind::Null,
224224
key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
225225
},
226226
node_max,
@@ -250,7 +250,7 @@ impl SerializedDepGraph {
250250

251251
let node = &mut nodes[index];
252252
// Make sure there's no duplicate indices in the dep graph.
253-
assert!(node_header.node().kind != DepKind::NULL && node.kind == DepKind::NULL);
253+
assert!(node_header.node().kind != DepKind::Null && node.kind == DepKind::Null);
254254
*node = node_header.node();
255255

256256
value_fingerprints[index] = node_header.value_fingerprint();
@@ -287,7 +287,7 @@ impl SerializedDepGraph {
287287
for (idx, node) in nodes.iter_enumerated() {
288288
if index[node.kind.as_usize()].insert(node.key_fingerprint, idx).is_some() {
289289
// Empty nodes and side effect nodes can have duplicates
290-
if node.kind != DepKind::NULL && node.kind != DepKind::SIDE_EFFECT {
290+
if node.kind != DepKind::Null && node.kind != DepKind::SideEffect {
291291
let name = node.kind.name();
292292
panic!(
293293
"Error: A dep graph node ({name}) does not have an unique index. \
@@ -361,7 +361,7 @@ impl SerializedNodeHeader {
361361
) -> Self {
362362
debug_assert_eq!(Self::TOTAL_BITS, Self::LEN_BITS + Self::WIDTH_BITS + Self::KIND_BITS);
363363

364-
let mut head = node.kind.as_inner();
364+
let mut head = node.kind.as_u16();
365365

366366
let free_bytes = edge_max_index.leading_zeros() as usize / 8;
367367
let bytes_per_index = (DEP_NODE_SIZE - free_bytes).saturating_sub(1);
@@ -408,7 +408,7 @@ impl SerializedNodeHeader {
408408
Unpacked {
409409
len: len.checked_sub(1),
410410
bytes_per_index: bytes_per_index as usize + 1,
411-
kind: DepKind::new(kind),
411+
kind: DepKind::from_u16(kind),
412412
index: SerializedDepNodeIndex::from_u32(index),
413413
key_fingerprint: Fingerprint::from_le_bytes(key_fingerprint).into(),
414414
value_fingerprint: Fingerprint::from_le_bytes(value_fingerprint),

compiler/rustc_middle/src/query/plumbing.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -588,11 +588,9 @@ macro_rules! define_feedable {
588588
let tcx = self.tcx;
589589
let erased_value = $name::provided_to_erased(tcx, value);
590590

591-
let dep_kind: dep_graph::DepKind = dep_graph::dep_kinds::$name;
592-
593591
$crate::query::inner::query_feed(
594592
tcx,
595-
dep_kind,
593+
dep_graph::DepKind::$name,
596594
&tcx.query_system.query_vtables.$name,
597595
&tcx.query_system.caches.$name,
598596
key,

compiler/rustc_middle/src/ty/context/impl_interner.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use rustc_span::{DUMMY_SP, Span, Symbol};
1313
use rustc_type_ir::lang_items::{SolverAdtLangItem, SolverLangItem, SolverTraitLangItem};
1414
use rustc_type_ir::{CollectAndApply, Interner, TypeFoldable, search_graph};
1515

16-
use crate::dep_graph::DepNodeIndex;
16+
use crate::dep_graph::{DepKind, DepNodeIndex};
1717
use crate::infer::canonical::CanonicalVarKinds;
1818
use crate::query::IntoQueryParam;
1919
use crate::traits::cache::WithDepNode;
@@ -77,7 +77,7 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
7777
}
7878
type DepNodeIndex = DepNodeIndex;
7979
fn with_cached_task<T>(self, task: impl FnOnce() -> T) -> (T, DepNodeIndex) {
80-
self.dep_graph.with_anon_task(self, crate::dep_graph::dep_kinds::TraitSelect, task)
80+
self.dep_graph.with_anon_task(self, DepKind::TraitSelect, task)
8181
}
8282
type Ty = Ty<'tcx>;
8383
type Tys = &'tcx List<Ty<'tcx>>;

compiler/rustc_query_impl/src/plumbing.rs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,7 @@ use rustc_index::Idx;
1414
use rustc_middle::bug;
1515
#[expect(unused_imports, reason = "used by doc comments")]
1616
use rustc_middle::dep_graph::DepKindVTable;
17-
use rustc_middle::dep_graph::{
18-
self, DepNode, DepNodeIndex, DepNodeKey, SerializedDepNodeIndex, dep_kinds,
19-
};
17+
use rustc_middle::dep_graph::{DepKind, DepNode, DepNodeIndex, DepNodeKey, SerializedDepNodeIndex};
2018
use rustc_middle::query::on_disk_cache::{
2119
AbsoluteBytePos, CacheDecoder, CacheEncoder, EncodedDepNodeIndex,
2220
};
@@ -123,7 +121,7 @@ pub fn collect_active_jobs_from_all_queries<'tcx>(
123121
if complete { Ok(job_map_out) } else { Err(job_map_out) }
124122
}
125123

126-
pub(super) fn try_mark_green<'tcx>(tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool {
124+
pub(super) fn try_mark_green<'tcx>(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> bool {
127125
tcx.dep_graph.try_mark_green(tcx, dep_node).is_some()
128126
}
129127

@@ -293,15 +291,15 @@ where
293291
} else {
294292
description
295293
};
296-
let span = if vtable.dep_kind == dep_graph::dep_kinds::def_span || reduce_queries {
294+
let span = if vtable.dep_kind == DepKind::def_span || reduce_queries {
297295
// The `def_span` query is used to calculate `default_span`,
298296
// so exit to avoid infinite recursion.
299297
None
300298
} else {
301299
Some(key.default_span(tcx))
302300
};
303301

304-
let def_kind = if vtable.dep_kind == dep_graph::dep_kinds::def_kind || reduce_queries {
302+
let def_kind = if vtable.dep_kind == DepKind::def_kind || reduce_queries {
305303
// Try to avoid infinite recursion.
306304
None
307305
} else {
@@ -461,7 +459,7 @@ pub(crate) fn force_from_dep_node_inner<'tcx, C: QueryCache, const FLAGS: QueryF
461459
// hit the cache instead of having to go through `force_from_dep_node`.
462460
// This assertion makes sure, we actually keep applying the solution above.
463461
debug_assert!(
464-
dep_node.kind != dep_kinds::codegen_unit,
462+
dep_node.kind != DepKind::codegen_unit,
465463
"calling force_from_dep_node() on dep_kinds::codegen_unit"
466464
);
467465

@@ -567,7 +565,7 @@ macro_rules! define_queries {
567565
QueryVTable {
568566
name: stringify!($name),
569567
eval_always: is_eval_always!([$($modifiers)*]),
570-
dep_kind: dep_graph::dep_kinds::$name,
568+
dep_kind: dep_graph::DepKind::$name,
571569
cycle_error_handling: cycle_error_handling!([$($modifiers)*]),
572570
query_state: std::mem::offset_of!(QueryStates<'tcx>, $name),
573571
query_cache: std::mem::offset_of!(QueryCaches<'tcx>, $name),

0 commit comments

Comments
 (0)