Skip to content

Commit 4aa4ce6

Browse files
authored
Rollup merge of #109621 - scottmcm:update-variantidx, r=compiler-errors
Refactor: `VariantIdx::from_u32(0)` -> `FIRST_VARIANT` Since structs are always `VariantIdx(0)`, there's a bunch of files where the only reason they had `VariantIdx` or `vec::Idx` imported at all was to get the first variant. So this uses a constant for that, and adds some doc-comments to `VariantIdx` while I'm there, since [it doesn't have any today](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_target/abi/struct.VariantIdx.html).
2 parents 776a8f4 + 0439d13 commit 4aa4ce6

File tree

25 files changed

+80
-78
lines changed

25 files changed

+80
-78
lines changed

compiler/rustc_abi/src/layout.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ pub trait LayoutCalculator {
4343
.max_by_key(|niche| niche.available(dl));
4444

4545
LayoutS {
46-
variants: Variants::Single { index: VariantIdx::new(0) },
46+
variants: Variants::Single { index: FIRST_VARIANT },
4747
fields: FieldsShape::Arbitrary {
4848
offsets: vec![Size::ZERO, b_offset],
4949
memory_index: vec![0, 1],
@@ -264,7 +264,7 @@ pub trait LayoutCalculator {
264264
abi = Abi::Uninhabited;
265265
}
266266
Some(LayoutS {
267-
variants: Variants::Single { index: VariantIdx::new(0) },
267+
variants: Variants::Single { index: FIRST_VARIANT },
268268
fields: FieldsShape::Arbitrary { offsets, memory_index },
269269
abi,
270270
largest_niche,
@@ -277,7 +277,7 @@ pub trait LayoutCalculator {
277277
let dl = self.current_data_layout();
278278
let dl = dl.borrow();
279279
LayoutS {
280-
variants: Variants::Single { index: VariantIdx::new(0) },
280+
variants: Variants::Single { index: FIRST_VARIANT },
281281
fields: FieldsShape::Primitive,
282282
abi: Abi::Uninhabited,
283283
largest_niche: None,
@@ -331,7 +331,7 @@ pub trait LayoutCalculator {
331331
}
332332
// If it's a struct, still compute a layout so that we can still compute the
333333
// field offsets.
334-
None => VariantIdx::new(0),
334+
None => FIRST_VARIANT,
335335
};
336336

337337
let is_struct = !is_enum ||
@@ -467,7 +467,7 @@ pub trait LayoutCalculator {
467467
.max_by_key(|(_i, layout)| layout.size.bytes())
468468
.map(|(i, _layout)| i)?;
469469

470-
let all_indices = (0..=variants.len() - 1).map(VariantIdx::new);
470+
let all_indices = variants.indices();
471471
let needs_disc =
472472
|index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
473473
let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap().index()
@@ -896,8 +896,8 @@ pub trait LayoutCalculator {
896896
let optimize = !repr.inhibit_union_abi_opt();
897897
let mut size = Size::ZERO;
898898
let mut abi = Abi::Aggregate { sized: true };
899-
let index = VariantIdx::new(0);
900-
for field in &variants[index] {
899+
let only_variant = &variants[FIRST_VARIANT];
900+
for field in only_variant {
901901
assert!(field.0.is_sized());
902902
align = align.max(field.align());
903903

@@ -930,8 +930,8 @@ pub trait LayoutCalculator {
930930
}
931931

932932
Some(LayoutS {
933-
variants: Variants::Single { index },
934-
fields: FieldsShape::Union(NonZeroUsize::new(variants[index].len())?),
933+
variants: Variants::Single { index: FIRST_VARIANT },
934+
fields: FieldsShape::Union(NonZeroUsize::new(only_variant.len())?),
935935
abi,
936936
largest_niche: None,
937937
align,

compiler/rustc_abi/src/lib.rs

+15-2
Original file line numberDiff line numberDiff line change
@@ -1380,8 +1380,21 @@ impl Niche {
13801380
}
13811381

13821382
rustc_index::newtype_index! {
1383+
/// The *source-order* index of a variant in a type.
1384+
///
1385+
/// For enums, these are always `0..variant_count`, regardless of any
1386+
/// custom discriminants that may have been defined, and including any
1387+
/// variants that may end up uninhabited due to field types. (Some of the
1388+
/// variants may not be present in a monomorphized ABI [`Variants`], but
1389+
/// those skipped variants are always counted when determining the *index*.)
1390+
///
1391+
/// `struct`s, `tuples`, and `unions`s are considered to have a single variant
1392+
/// with variant index zero, aka [`FIRST_VARIANT`].
13831393
#[derive(HashStable_Generic)]
1384-
pub struct VariantIdx {}
1394+
pub struct VariantIdx {
1395+
/// Equivalent to `VariantIdx(0)`.
1396+
const FIRST_VARIANT = 0;
1397+
}
13851398
}
13861399

13871400
#[derive(PartialEq, Eq, Hash, Clone)]
@@ -1422,7 +1435,7 @@ impl LayoutS {
14221435
let size = scalar.size(cx);
14231436
let align = scalar.align(cx);
14241437
LayoutS {
1425-
variants: Variants::Single { index: VariantIdx::new(0) },
1438+
variants: Variants::Single { index: FIRST_VARIANT },
14261439
fields: FieldsShape::Primitive,
14271440
abi: Abi::Scalar(scalar),
14281441
largest_niche,

compiler/rustc_borrowck/src/type_check/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc_hir as hir;
1414
use rustc_hir::def::DefKind;
1515
use rustc_hir::def_id::LocalDefId;
1616
use rustc_hir::lang_items::LangItem;
17-
use rustc_index::vec::{Idx, IndexVec};
17+
use rustc_index::vec::IndexVec;
1818
use rustc_infer::infer::canonical::QueryRegionConstraints;
1919
use rustc_infer::infer::outlives::env::RegionBoundPairs;
2020
use rustc_infer::infer::region_constraints::RegionConstraintData;
@@ -36,7 +36,7 @@ use rustc_middle::ty::{
3636
};
3737
use rustc_span::def_id::CRATE_DEF_ID;
3838
use rustc_span::{Span, DUMMY_SP};
39-
use rustc_target::abi::VariantIdx;
39+
use rustc_target::abi::FIRST_VARIANT;
4040
use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
4141
use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
4242
use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
@@ -812,7 +812,7 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
812812
},
813813
PlaceTy { ty, variant_index: None } => match *ty.kind() {
814814
ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
815-
(adt_def.variant(VariantIdx::new(0)), substs)
815+
(adt_def.variant(FIRST_VARIANT), substs)
816816
}
817817
ty::Closure(_, substs) => {
818818
return match substs

compiler/rustc_codegen_cranelift/src/base.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -785,7 +785,7 @@ fn codegen_stmt<'tcx>(
785785
let variant_dest = lval.downcast_variant(fx, variant_index);
786786
(variant_index, variant_dest, active_field_index)
787787
}
788-
_ => (VariantIdx::from_u32(0), lval, None),
788+
_ => (FIRST_VARIANT, lval, None),
789789
};
790790
if active_field_index.is_some() {
791791
assert_eq!(operands.len(), 1);

compiler/rustc_codegen_cranelift/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ mod prelude {
8686
self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
8787
TypeFoldable, TypeVisitableExt, UintTy,
8888
};
89-
pub(crate) use rustc_target::abi::{Abi, Scalar, Size, VariantIdx};
89+
pub(crate) use rustc_target::abi::{Abi, Scalar, Size, VariantIdx, FIRST_VARIANT};
9090

9191
pub(crate) use rustc_data_structures::fx::FxHashMap;
9292

compiler/rustc_codegen_cranelift/src/unsize.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ pub(crate) fn coerce_unsized_into<'tcx>(
146146
(&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
147147
assert_eq!(def_a, def_b);
148148

149-
for i in 0..def_a.variant(VariantIdx::new(0)).fields.len() {
149+
for i in 0..def_a.variant(FIRST_VARIANT).fields.len() {
150150
let src_f = src.value_field(fx, mir::Field::new(i));
151151
let dst_f = dst.place_field(fx, mir::Field::new(i));
152152

compiler/rustc_codegen_ssa/src/base.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ use rustc_data_structures::sync::ParallelIterator;
2424
use rustc_hir as hir;
2525
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
2626
use rustc_hir::lang_items::LangItem;
27-
use rustc_index::vec::Idx;
2827
use rustc_metadata::EncodedMetadata;
2928
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
3029
use rustc_middle::middle::exported_symbols;
@@ -40,7 +39,7 @@ use rustc_session::Session;
4039
use rustc_span::symbol::sym;
4140
use rustc_span::Symbol;
4241
use rustc_span::{DebuggerVisualizerFile, DebuggerVisualizerType};
43-
use rustc_target::abi::{Align, VariantIdx};
42+
use rustc_target::abi::{Align, FIRST_VARIANT};
4443

4544
use std::collections::BTreeSet;
4645
use std::time::{Duration, Instant};
@@ -307,7 +306,7 @@ pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
307306
(&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
308307
assert_eq!(def_a, def_b);
309308

310-
for i in 0..def_a.variant(VariantIdx::new(0)).fields.len() {
309+
for i in 0..def_a.variant(FIRST_VARIANT).fields.len() {
311310
let src_f = src.project_field(bx, i);
312311
let dst_f = dst.project_field(bx, i);
313312

compiler/rustc_codegen_ssa/src/mir/rvalue.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use rustc_middle::ty::cast::{CastTy, IntTy};
1313
use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf};
1414
use rustc_middle::ty::{self, adjustment::PointerCast, Instance, Ty, TyCtxt};
1515
use rustc_span::source_map::{Span, DUMMY_SP};
16-
use rustc_target::abi::{self, VariantIdx};
16+
use rustc_target::abi::{self, FIRST_VARIANT};
1717

1818
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1919
#[instrument(level = "trace", skip(self, bx))]
@@ -118,7 +118,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
118118
let variant_dest = dest.project_downcast(bx, variant_index);
119119
(variant_index, variant_dest, active_field_index)
120120
}
121-
_ => (VariantIdx::from_u32(0), dest, None),
121+
_ => (FIRST_VARIANT, dest, None),
122122
};
123123
if active_field_index.is_some() {
124124
assert_eq!(operands.len(), 1);

compiler/rustc_const_eval/src/const_eval/valtrees.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use crate::interpret::{
88
use crate::interpret::{MPlaceTy, Value};
99
use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt};
1010
use rustc_span::source_map::DUMMY_SP;
11-
use rustc_target::abi::{Align, VariantIdx};
11+
use rustc_target::abi::{Align, VariantIdx, FIRST_VARIANT};
1212

1313
#[instrument(skip(ecx), level = "debug")]
1414
fn branches<'tcx>(
@@ -412,7 +412,7 @@ fn valtree_into_mplace<'tcx>(
412412

413413
let inner_ty = match ty.kind() {
414414
ty::Adt(def, substs) => {
415-
def.variant(VariantIdx::from_u32(0)).fields[i].ty(tcx, substs)
415+
def.variant(FIRST_VARIANT).fields[i].ty(tcx, substs)
416416
}
417417
ty::Tuple(inner_tys) => inner_tys[i],
418418
_ => bug!("unexpected unsized type {:?}", ty),

compiler/rustc_const_eval/src/interpret/place.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustc_ast::Mutability;
88
use rustc_middle::mir;
99
use rustc_middle::ty;
1010
use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
11-
use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size, VariantIdx};
11+
use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size, FIRST_VARIANT};
1212

1313
use super::{
1414
alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg,
@@ -796,7 +796,7 @@ where
796796
let variant_dest = self.place_downcast(&dest, variant_index)?;
797797
(variant_index, variant_dest, active_field_index)
798798
}
799-
_ => (VariantIdx::from_u32(0), dest.clone(), None),
799+
_ => (FIRST_VARIANT, dest.clone(), None),
800800
};
801801
if active_field_index.is_some() {
802802
assert_eq!(operands.len(), 1);

compiler/rustc_const_eval/src/transform/validate.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use rustc_middle::ty::{self, InstanceDef, ParamEnv, Ty, TyCtxt, TypeVisitableExt
1717
use rustc_mir_dataflow::impls::MaybeStorageLive;
1818
use rustc_mir_dataflow::storage::always_storage_live_locals;
1919
use rustc_mir_dataflow::{Analysis, ResultsCursor};
20-
use rustc_target::abi::{Size, VariantIdx};
20+
use rustc_target::abi::{Size, FIRST_VARIANT};
2121

2222
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2323
enum EdgeKind {
@@ -359,7 +359,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
359359
check_equal(self, location, *f_ty);
360360
}
361361
ty::Adt(adt_def, substs) => {
362-
let var = parent_ty.variant_index.unwrap_or(VariantIdx::from_u32(0));
362+
let var = parent_ty.variant_index.unwrap_or(FIRST_VARIANT);
363363
let Some(field) = adt_def.variant(var).fields.get(f.as_usize()) else {
364364
fail_out_of_bounds(self, location);
365365
return;

compiler/rustc_hir_typeck/src/expr_use_visitor.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,11 @@ use rustc_hir as hir;
1414
use rustc_hir::def::Res;
1515
use rustc_hir::def_id::LocalDefId;
1616
use rustc_hir::PatKind;
17-
use rustc_index::vec::Idx;
1817
use rustc_infer::infer::InferCtxt;
1918
use rustc_middle::hir::place::ProjectionKind;
2019
use rustc_middle::mir::FakeReadCause;
2120
use rustc_middle::ty::{self, adjustment, AdtKind, Ty, TyCtxt};
22-
use rustc_target::abi::VariantIdx;
21+
use rustc_target::abi::FIRST_VARIANT;
2322
use ty::BorrowKind::ImmBorrow;
2423

2524
use crate::mem_categorization as mc;
@@ -549,7 +548,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
549548
&*with_expr,
550549
with_place.clone(),
551550
with_field.ty(self.tcx(), substs),
552-
ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
551+
ProjectionKind::Field(f_index as u32, FIRST_VARIANT),
553552
);
554553
self.delegate_consume(&field_place, field_place.hir_id);
555554
}

compiler/rustc_hir_typeck/src/mem_categorization.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,9 @@ use rustc_hir::def::{CtorOf, DefKind, Res};
5959
use rustc_hir::def_id::LocalDefId;
6060
use rustc_hir::pat_util::EnumerateAndAdjustIterator;
6161
use rustc_hir::PatKind;
62-
use rustc_index::vec::Idx;
6362
use rustc_infer::infer::InferCtxt;
6463
use rustc_span::Span;
65-
use rustc_target::abi::VariantIdx;
64+
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
6665
use rustc_trait_selection::infer::InferCtxtExt;
6766

6867
pub(crate) trait HirNode {
@@ -331,7 +330,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
331330
expr,
332331
base,
333332
expr_ty,
334-
ProjectionKind::Field(field_idx as u32, VariantIdx::new(0)),
333+
ProjectionKind::Field(field_idx as u32, FIRST_VARIANT),
335334
))
336335
}
337336

@@ -561,7 +560,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
561560
| Res::SelfTyParam { .. }
562561
| Res::SelfTyAlias { .. } => {
563562
// Structs and Unions have only have one variant.
564-
Ok(VariantIdx::new(0))
563+
Ok(FIRST_VARIANT)
565564
}
566565
_ => bug!("expected ADT path, found={:?}", res),
567566
}
@@ -675,7 +674,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
675674

676675
for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) {
677676
let subpat_ty = self.pat_ty_adjusted(subpat)?;
678-
let projection_kind = ProjectionKind::Field(i as u32, VariantIdx::new(0));
677+
let projection_kind = ProjectionKind::Field(i as u32, FIRST_VARIANT);
679678
let sub_place =
680679
self.cat_projection(pat, place_with_id.clone(), subpat_ty, projection_kind);
681680
self.cat_pattern_(sub_place, subpat, op)?;

compiler/rustc_hir_typeck/src/upvar.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,7 @@ use rustc_span::{BytePos, Pos, Span, Symbol};
4949
use rustc_trait_selection::infer::InferCtxtExt;
5050

5151
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
52-
use rustc_index::vec::Idx;
53-
use rustc_target::abi::VariantIdx;
52+
use rustc_target::abi::FIRST_VARIANT;
5453

5554
use std::iter;
5655

@@ -1406,7 +1405,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
14061405
ProjectionKind::Field(..)
14071406
))
14081407
);
1409-
def.variants().get(VariantIdx::new(0)).unwrap().fields.iter().enumerate().any(
1408+
def.variants().get(FIRST_VARIANT).unwrap().fields.iter().enumerate().any(
14101409
|(i, field)| {
14111410
let paths_using_field = captured_by_move_projs
14121411
.iter()

compiler/rustc_lint/src/builtin.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ use rustc_hir::def::{DefKind, Res};
5858
use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdSet, CRATE_DEF_ID};
5959
use rustc_hir::intravisit::FnKind as HirFnKind;
6060
use rustc_hir::{Body, FnDecl, ForeignItemKind, GenericParamKind, Node, PatKind, PredicateOrigin};
61-
use rustc_index::vec::Idx;
6261
use rustc_middle::lint::in_external_macro;
6362
use rustc_middle::ty::layout::{LayoutError, LayoutOf};
6463
use rustc_middle::ty::print::with_no_trimmed_paths;
@@ -69,7 +68,7 @@ use rustc_span::edition::Edition;
6968
use rustc_span::source_map::Spanned;
7069
use rustc_span::symbol::{kw, sym, Ident, Symbol};
7170
use rustc_span::{BytePos, InnerSpan, Span};
72-
use rustc_target::abi::{Abi, VariantIdx};
71+
use rustc_target::abi::{Abi, FIRST_VARIANT};
7372
use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt};
7473
use rustc_trait_selection::traits::{self, misc::type_allowed_to_implement_copy};
7574

@@ -2788,7 +2787,7 @@ impl ClashingExternDeclarations {
27882787
);
27892788
if is_transparent && !is_non_null {
27902789
debug_assert_eq!(def.variants().len(), 1);
2791-
let v = &def.variant(VariantIdx::new(0));
2790+
let v = &def.variant(FIRST_VARIANT);
27922791
// continue with `ty`'s non-ZST field,
27932792
// otherwise `ty` is a ZST and we can return
27942793
if let Some(field) = transparent_newtype_field(tcx, v) {

compiler/rustc_middle/src/ty/adt.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
1010
use rustc_hir as hir;
1111
use rustc_hir::def::{CtorKind, DefKind, Res};
1212
use rustc_hir::def_id::DefId;
13-
use rustc_index::vec::{Idx, IndexVec};
13+
use rustc_index::vec::IndexVec;
1414
use rustc_query_system::ich::StableHashingContext;
1515
use rustc_session::DataTypeKind;
1616
use rustc_span::symbol::sym;
17-
use rustc_target::abi::{ReprOptions, VariantIdx};
17+
use rustc_target::abi::{ReprOptions, VariantIdx, FIRST_VARIANT};
1818

1919
use std::cell::RefCell;
2020
use std::cmp::Ordering;
@@ -228,7 +228,7 @@ impl AdtDefData {
228228
AdtKind::Struct => AdtFlags::IS_STRUCT,
229229
};
230230

231-
if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor.is_some() {
231+
if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
232232
flags |= AdtFlags::HAS_CTOR;
233233
}
234234

@@ -357,7 +357,7 @@ impl<'tcx> AdtDef<'tcx> {
357357
/// Asserts this is a struct or union and returns its unique variant.
358358
pub fn non_enum_variant(self) -> &'tcx VariantDef {
359359
assert!(self.is_struct() || self.is_union());
360-
&self.variant(VariantIdx::new(0))
360+
&self.variant(FIRST_VARIANT)
361361
}
362362

363363
#[inline]
@@ -493,7 +493,7 @@ impl<'tcx> AdtDef<'tcx> {
493493

494494
#[inline]
495495
pub fn variant_range(self) -> Range<VariantIdx> {
496-
VariantIdx::new(0)..VariantIdx::new(self.variants().len())
496+
FIRST_VARIANT..self.variants().next_index()
497497
}
498498

499499
/// Computes the discriminant value used by a specific variant.

0 commit comments

Comments
 (0)