Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 0439d13

Browse files
committedMar 26, 2023
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.
1 parent 96bd50d commit 0439d13

File tree

25 files changed

+80
-78
lines changed

25 files changed

+80
-78
lines changed
 

‎compiler/rustc_abi/src/layout.rs

Lines changed: 9 additions & 9 deletions
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

Lines changed: 15 additions & 2 deletions
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

Lines changed: 3 additions & 3 deletions
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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 2 additions & 3 deletions
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

Lines changed: 2 additions & 2 deletions
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

Lines changed: 2 additions & 2 deletions
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

Lines changed: 2 additions & 2 deletions
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

Lines changed: 2 additions & 2 deletions
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

Lines changed: 2 additions & 3 deletions
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

Lines changed: 4 additions & 5 deletions
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

Lines changed: 2 additions & 3 deletions
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

Lines changed: 2 additions & 3 deletions
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

Lines changed: 5 additions & 5 deletions
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.

‎compiler/rustc_middle/src/ty/sty.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use rustc_index::vec::Idx;
2222
use rustc_macros::HashStable;
2323
use rustc_span::symbol::{kw, sym, Symbol};
2424
use rustc_span::Span;
25-
use rustc_target::abi::VariantIdx;
25+
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
2626
use rustc_target::spec::abi::{self, Abi};
2727
use std::borrow::Cow;
2828
use std::cmp::Ordering;
@@ -517,8 +517,7 @@ impl<'tcx> GeneratorSubsts<'tcx> {
517517
#[inline]
518518
pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
519519
// FIXME requires optimized MIR
520-
let num_variants = tcx.generator_layout(def_id).unwrap().variant_fields.len();
521-
VariantIdx::new(0)..VariantIdx::new(num_variants)
520+
FIRST_VARIANT..tcx.generator_layout(def_id).unwrap().variant_fields.next_index()
522521
}
523522

524523
/// The discriminant for the given variant. Panics if the `variant_index` is

‎compiler/rustc_mir_build/src/build/expr/as_place.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,7 @@ use rustc_middle::thir::*;
1313
use rustc_middle::ty::AdtDef;
1414
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, Variance};
1515
use rustc_span::Span;
16-
use rustc_target::abi::VariantIdx;
17-
18-
use rustc_index::vec::Idx;
16+
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
1917

2018
use std::assert_matches::assert_matches;
2119
use std::iter;
@@ -91,7 +89,7 @@ fn convert_to_hir_projections_and_truncate_for_capture(
9189
let hir_projection = match mir_projection {
9290
ProjectionElem::Deref => HirProjectionKind::Deref,
9391
ProjectionElem::Field(field, _) => {
94-
let variant = variant.unwrap_or(VariantIdx::new(0));
92+
let variant = variant.unwrap_or(FIRST_VARIANT);
9593
HirProjectionKind::Field(field.index() as u32, variant)
9694
}
9795
ProjectionElem::Downcast(.., idx) => {

‎compiler/rustc_mir_build/src/thir/cx/expr.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use rustc_middle::ty::{
2020
self, AdtKind, InlineConstSubsts, InlineConstSubstsParts, ScalarInt, Ty, UpvarSubsts, UserType,
2121
};
2222
use rustc_span::{sym, Span};
23-
use rustc_target::abi::VariantIdx;
23+
use rustc_target::abi::FIRST_VARIANT;
2424

2525
impl<'tcx> Cx<'tcx> {
2626
pub(crate) fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId {
@@ -357,7 +357,7 @@ impl<'tcx> Cx<'tcx> {
357357
Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => {
358358
Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id)))
359359
}
360-
Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
360+
Res::SelfCtor(..) => Some((adt_def, FIRST_VARIANT)),
361361
_ => None,
362362
})
363363
} else {
@@ -510,7 +510,7 @@ impl<'tcx> Cx<'tcx> {
510510
debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
511511
ExprKind::Adt(Box::new(AdtExpr {
512512
adt_def: *adt,
513-
variant_index: VariantIdx::new(0),
513+
variant_index: FIRST_VARIANT,
514514
substs,
515515
user_ty,
516516
fields: self.field_refs(fields),
@@ -732,7 +732,7 @@ impl<'tcx> Cx<'tcx> {
732732
}
733733
hir::ExprKind::Field(ref source, ..) => ExprKind::Field {
734734
lhs: self.mirror_expr(source),
735-
variant_index: VariantIdx::new(0),
735+
variant_index: FIRST_VARIANT,
736736
name: Field::new(self.typeck_results.field_index(expr.hir_id)),
737737
},
738738
hir::ExprKind::Cast(ref source, ref cast_ty) => {

‎compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ use rustc_middle::ty::{self, Ty, TyCtxt, VariantDef};
6060
use rustc_middle::{middle::stability::EvalResult, mir::interpret::ConstValue};
6161
use rustc_session::lint;
6262
use rustc_span::{Span, DUMMY_SP};
63-
use rustc_target::abi::{Integer, Size, VariantIdx};
63+
use rustc_target::abi::{Integer, Size, VariantIdx, FIRST_VARIANT};
6464

6565
use self::Constructor::*;
6666
use self::SliceKind::*;
@@ -706,7 +706,7 @@ impl<'tcx> Constructor<'tcx> {
706706
Variant(idx) => idx,
707707
Single => {
708708
assert!(!adt.is_enum());
709-
VariantIdx::new(0)
709+
FIRST_VARIANT
710710
}
711711
_ => bug!("bad constructor {:?} for adt {:?}", self, adt),
712712
}

‎compiler/rustc_mir_dataflow/src/elaborate_drops.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_middle::traits::Reveal;
77
use rustc_middle::ty::subst::SubstsRef;
88
use rustc_middle::ty::util::IntTypeExt;
99
use rustc_middle::ty::{self, Ty, TyCtxt};
10-
use rustc_target::abi::VariantIdx;
10+
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
1111
use std::{fmt, iter};
1212

1313
/// The value of an inserted drop flag.
@@ -468,7 +468,7 @@ where
468468
let fields = self.move_paths_for_fields(
469469
self.place,
470470
self.path,
471-
&adt.variant(VariantIdx::new(0)),
471+
&adt.variant(FIRST_VARIANT),
472472
substs,
473473
);
474474
self.drop_ladder(fields, succ, unwind)
@@ -894,7 +894,7 @@ where
894894
let unit_temp = Place::from(self.new_temp(tcx.mk_unit()));
895895
let free_func = tcx.require_lang_item(LangItem::BoxFree, Some(self.source_info.span));
896896
let args = adt
897-
.variant(VariantIdx::new(0))
897+
.variant(FIRST_VARIANT)
898898
.fields
899899
.iter()
900900
.enumerate()

‎compiler/rustc_mir_transform/src/inline.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use rustc_middle::mir::*;
1010
use rustc_middle::ty::{self, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
1111
use rustc_session::config::OptLevel;
1212
use rustc_span::{hygiene::ExpnKind, ExpnData, LocalExpnId, Span};
13-
use rustc_target::abi::VariantIdx;
13+
use rustc_target::abi::FIRST_VARIANT;
1414
use rustc_target::spec::abi::Abi;
1515

1616
use crate::simplify::{remove_dead_blocks, CfgSimplifier};
@@ -911,7 +911,7 @@ impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> {
911911
check_equal(self, *f_ty);
912912
}
913913
ty::Adt(adt_def, substs) => {
914-
let var = parent_ty.variant_index.unwrap_or(VariantIdx::from_u32(0));
914+
let var = parent_ty.variant_index.unwrap_or(FIRST_VARIANT);
915915
let Some(field) = adt_def.variant(var).fields.get(f.as_usize()) else {
916916
self.validation = Err("malformed MIR");
917917
return;

‎compiler/rustc_mir_transform/src/shim.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use rustc_middle::mir::*;
55
use rustc_middle::ty::query::Providers;
66
use rustc_middle::ty::InternalSubsts;
77
use rustc_middle::ty::{self, EarlyBinder, GeneratorSubsts, Ty, TyCtxt};
8-
use rustc_target::abi::VariantIdx;
8+
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
99

1010
use rustc_index::vec::{Idx, IndexVec};
1111

@@ -816,11 +816,8 @@ pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
816816

817817
let source_info = SourceInfo::outermost(span);
818818

819-
let variant_index = if adt_def.is_enum() {
820-
adt_def.variant_index_with_ctor_id(ctor_id)
821-
} else {
822-
VariantIdx::new(0)
823-
};
819+
let variant_index =
820+
if adt_def.is_enum() { adt_def.variant_index_with_ctor_id(ctor_id) } else { FIRST_VARIANT };
824821

825822
// Generate the following MIR:
826823
//

‎compiler/rustc_ty_utils/src/consts.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustc_middle::ty::abstract_const::CastKind;
88
use rustc_middle::ty::{self, Expr, TyCtxt, TypeVisitableExt};
99
use rustc_middle::{mir, thir};
1010
use rustc_span::Span;
11-
use rustc_target::abi::VariantIdx;
11+
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
1212

1313
use std::iter;
1414

@@ -44,7 +44,7 @@ pub(crate) fn destructure_const<'tcx>(
4444
let (head, rest) = branches.split_first().unwrap();
4545
(VariantIdx::from_u32(head.unwrap_leaf().try_to_u32().unwrap()), rest)
4646
} else {
47-
(VariantIdx::from_u32(0), branches)
47+
(FIRST_VARIANT, branches)
4848
};
4949
let fields = &def.variant(variant_idx).fields;
5050
let mut field_consts = Vec::with_capacity(fields.len());

‎compiler/rustc_ty_utils/src/layout.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use hir::def_id::DefId;
22
use rustc_hir as hir;
33
use rustc_index::bit_set::BitSet;
4-
use rustc_index::vec::{Idx, IndexVec};
4+
use rustc_index::vec::IndexVec;
55
use rustc_middle::mir::{GeneratorLayout, GeneratorSavedLocal};
66
use rustc_middle::ty::layout::{
77
IntegerExt, LayoutCx, LayoutError, LayoutOf, TyAndLayout, MAX_SIMD_LANES,
@@ -227,7 +227,7 @@ fn layout_of_uncached<'tcx>(
227227
let largest_niche = if count != 0 { element.largest_niche } else { None };
228228

229229
tcx.mk_layout(LayoutS {
230-
variants: Variants::Single { index: VariantIdx::new(0) },
230+
variants: Variants::Single { index: FIRST_VARIANT },
231231
fields: FieldsShape::Array { stride: element.size, count },
232232
abi,
233233
largest_niche,
@@ -238,7 +238,7 @@ fn layout_of_uncached<'tcx>(
238238
ty::Slice(element) => {
239239
let element = cx.layout_of(element)?;
240240
tcx.mk_layout(LayoutS {
241-
variants: Variants::Single { index: VariantIdx::new(0) },
241+
variants: Variants::Single { index: FIRST_VARIANT },
242242
fields: FieldsShape::Array { stride: element.size, count: 0 },
243243
abi: Abi::Aggregate { sized: false },
244244
largest_niche: None,
@@ -247,7 +247,7 @@ fn layout_of_uncached<'tcx>(
247247
})
248248
}
249249
ty::Str => tcx.mk_layout(LayoutS {
250-
variants: Variants::Single { index: VariantIdx::new(0) },
250+
variants: Variants::Single { index: FIRST_VARIANT },
251251
fields: FieldsShape::Array { stride: Size::from_bytes(1), count: 0 },
252252
abi: Abi::Aggregate { sized: false },
253253
largest_niche: None,
@@ -399,7 +399,7 @@ fn layout_of_uncached<'tcx>(
399399
};
400400

401401
tcx.mk_layout(LayoutS {
402-
variants: Variants::Single { index: VariantIdx::new(0) },
402+
variants: Variants::Single { index: FIRST_VARIANT },
403403
fields,
404404
abi: Abi::Vector { element: e_abi, count: e_len },
405405
largest_niche: e_ly.largest_niche,

0 commit comments

Comments
 (0)
Please sign in to comment.