4747//!
4848//! [dependency graph]: https://rustc-dev-guide.rust-lang.org/query.html
4949
50- use std:: fmt;
5150use std:: hash:: Hash ;
51+ use std:: { fmt, mem} ;
5252
5353use rustc_data_structures:: fingerprint:: { Fingerprint , PackedFingerprint } ;
5454use rustc_data_structures:: stable_hasher:: { StableHasher , StableOrd , ToStableHashKey } ;
@@ -66,11 +66,23 @@ use crate::ty::{TyCtxt, tls};
6666impl DepKind {
6767 #[ inline]
6868 pub ( crate ) fn from_u16 ( u : u16 ) -> Self {
69+ // Statically assert that every u16 up to `DepKind::MAX` can be transmuted
70+ // into a `DepKind` that round-trips back to that number.
71+ const _: ( ) = {
72+ assert ! ( DepKind :: MAX as usize + 1 == DepKind :: NUM_VARIANTS ) ;
73+ let mut i = 0 ;
74+ while i <= DepKind :: MAX {
75+ let dep_kind = unsafe { mem:: transmute :: < u16 , DepKind > ( i) } ;
76+ assert ! ( dep_kind as u16 == i) ;
77+ i += 1 ;
78+ }
79+ } ;
80+
6981 if u > Self :: MAX {
7082 panic ! ( "Invalid DepKind {u}" ) ;
7183 }
72- // SAFETY: See comment on DEP_KIND_NUM_VARIANTS
73- unsafe { std :: mem:: transmute ( u) }
84+ // SAFETY: See the static assertion above.
85+ unsafe { mem:: transmute ( u) }
7486 }
7587
7688 #[ inline]
@@ -85,7 +97,7 @@ impl DepKind {
8597
8698 /// This is the highest value a `DepKind` can have. It's used during encoding to
8799 /// pack information into the unused bits.
88- pub ( crate ) const MAX : u16 = DEP_KIND_NUM_VARIANTS - 1 ;
100+ pub ( crate ) const MAX : u16 = ( DepKind :: NUM_VARIANTS - 1 ) as u16 ;
89101}
90102
91103/// Combination of a [`DepKind`] and a key fingerprint that uniquely identifies
@@ -293,24 +305,10 @@ macro_rules! define_dep_nodes {
293305 $( $( #[ $q_attr] ) * $q_name, ) *
294306 }
295307
296- // This computes the number of dep kind variants. Along the way, it sanity-checks that the
297- // discriminants of the variants have been assigned consecutively from 0 so that they can
298- // be used as a dense index, and that all discriminants fit in a `u16`.
299- pub ( crate ) const DEP_KIND_NUM_VARIANTS : u16 = {
300- let deps = & [
301- $( DepKind :: $nq_name, ) *
302- $( DepKind :: $q_name, ) *
303- ] ;
304- let mut i = 0 ;
305- while i < deps. len( ) {
306- if i != deps[ i] . as_usize( ) {
307- panic!( ) ;
308- }
309- i += 1 ;
310- }
311- assert!( deps. len( ) <= u16 :: MAX as usize ) ;
312- deps. len( ) as u16
313- } ;
308+ impl DepKind {
309+ /// The total number of variants in [`DepKind`].
310+ pub const NUM_VARIANTS : usize = ${ count( $nq_name) } + ${ count( $q_name) } ;
311+ }
314312
315313 pub ( super ) fn dep_kind_from_label_string( label: & str ) -> Result <DepKind , ( ) > {
316314 match label {
0 commit comments