Skip to content

Various minor Idx-related tweaks #110394

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions compiler/rustc_abi/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,8 +461,8 @@ pub trait LayoutCalculator {
let all_indices = variants.indices();
let needs_disc =
|index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap().index()
..=all_indices.rev().find(|v| needs_disc(*v)).unwrap().index();
let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap()
..=all_indices.rev().find(|v| needs_disc(*v)).unwrap();

let count = niche_variants.size_hint().1.unwrap() as u128;

Expand Down Expand Up @@ -560,8 +560,7 @@ pub trait LayoutCalculator {
tag: niche_scalar,
tag_encoding: TagEncoding::Niche {
untagged_variant: largest_variant_index,
niche_variants: (VariantIdx::new(*niche_variants.start())
..=VariantIdx::new(*niche_variants.end())),
niche_variants,
niche_start,
},
tag_field: 0,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_abi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use bitflags::bitflags;
use rustc_data_structures::intern::Interned;
#[cfg(feature = "nightly")]
use rustc_data_structures::stable_hasher::StableOrd;
use rustc_index::vec::{Idx, IndexSlice, IndexVec};
use rustc_index::vec::{IndexSlice, IndexVec};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh? How did this not issue dead code lint before? O_o

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The layout.rs file has use super::*; rather than doing its own imports. So it's the change in the other file that lets this be removed.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I see.

#[cfg(feature = "nightly")]
use rustc_macros::HashStable_Generic;
#[cfg(feature = "nightly")]
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_ast/src/node_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ rustc_index::newtype_index! {
///
/// [`DefId`]: rustc_span::def_id::DefId
#[debug_format = "NodeId({})"]
pub struct NodeId {}
pub struct NodeId {
/// The [`NodeId`] used to represent the root of the crate.
const CRATE_NODE_ID = 0;
}
}

rustc_data_structures::define_id_collections!(NodeMap, NodeSet, NodeMapEntry, NodeId);

/// The [`NodeId`] used to represent the root of the crate.
pub const CRATE_NODE_ID: NodeId = NodeId::from_u32(0);

/// When parsing and at the beginning of doing expansions, we initially give all AST nodes
/// this dummy AST [`NodeId`]. Then, during a later phase of expansion, we renumber them
/// to have small, positive IDs.
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_borrowck/src/diagnostics/var_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use crate::region_infer::RegionInferenceContext;
use crate::Upvar;
use rustc_index::vec::{Idx, IndexSlice};
use rustc_index::vec::IndexSlice;
use rustc_middle::mir::{Body, Local};
use rustc_middle::ty::{RegionVid, TyCtxt};
use rustc_span::source_map::Span;
Expand Down Expand Up @@ -117,7 +117,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
argument_index: usize,
) -> (Option<Symbol>, Span) {
let implicit_inputs = self.universal_regions().defining_ty.implicit_inputs();
let argument_local = Local::new(implicit_inputs + argument_index + 1);
let argument_local = Local::from_usize(implicit_inputs + argument_index + 1);
debug!("get_argument_name_and_span_for_region: argument_local={argument_local:?}");

let argument_name = local_names[argument_local];
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_borrowck/src/facts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::location::{LocationIndex, LocationTable};
use crate::BorrowIndex;
use polonius_engine::AllFacts as PoloniusFacts;
use polonius_engine::Atom;
use rustc_index::vec::Idx;
use rustc_middle::mir::Local;
use rustc_middle::ty::{RegionVid, TyCtxt};
use rustc_mir_dataflow::move_paths::MovePathIndex;
Expand Down Expand Up @@ -93,13 +92,13 @@ impl AllFactsExt for AllFacts {

impl Atom for BorrowIndex {
fn index(self) -> usize {
Idx::index(self)
self.as_usize()
}
}

impl Atom for LocationIndex {
fn index(self) -> usize {
Idx::index(self)
self.as_usize()
}
}

Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_borrowck/src/location.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![deny(rustc::untranslatable_diagnostic)]
#![deny(rustc::diagnostic_outside_of_impl)]
use rustc_index::vec::{Idx, IndexVec};
use rustc_index::vec::IndexVec;
use rustc_middle::mir::{BasicBlock, Body, Location};

/// Maps between a MIR Location, which identifies a particular
Expand Down Expand Up @@ -50,19 +50,19 @@ impl LocationTable {
}

pub fn all_points(&self) -> impl Iterator<Item = LocationIndex> {
(0..self.num_points).map(LocationIndex::new)
(0..self.num_points).map(LocationIndex::from_usize)
}

pub fn start_index(&self, location: Location) -> LocationIndex {
let Location { block, statement_index } = location;
let start_index = self.statements_before_block[block];
LocationIndex::new(start_index + statement_index * 2)
LocationIndex::from_usize(start_index + statement_index * 2)
}

pub fn mid_index(&self, location: Location) -> LocationIndex {
let Location { block, statement_index } = location;
let start_index = self.statements_before_block[block];
LocationIndex::new(start_index + statement_index * 2 + 1)
LocationIndex::from_usize(start_index + statement_index * 2 + 1)
}

pub fn to_location(&self, index: LocationIndex) -> RichLocation {
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_borrowck/src/nll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use rustc_hir::def_id::LocalDefId;
use rustc_index::vec::IndexSlice;
use rustc_middle::mir::{create_dump_file, dump_enabled, dump_mir, PassWhere};
use rustc_middle::mir::{
BasicBlock, Body, ClosureOutlivesSubject, ClosureRegionRequirements, LocalKind, Location,
Promoted,
Body, ClosureOutlivesSubject, ClosureRegionRequirements, LocalKind, Location, Promoted,
START_BLOCK,
};
use rustc_middle::ty::{self, OpaqueHiddenType, TyCtxt};
use rustc_span::symbol::sym;
Expand Down Expand Up @@ -94,8 +94,8 @@ fn populate_polonius_move_facts(
}
}

let fn_entry_start = location_table
.start_index(Location { block: BasicBlock::from_u32(0u32), statement_index: 0 });
let fn_entry_start =
location_table.start_index(Location { block: START_BLOCK, statement_index: 0 });

// initialized_at
for init in move_data.inits.iter() {
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_borrowck/src/type_check/input_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
//! `RETURN_PLACE` the MIR arguments) are always fully normalized (and
//! contain revealed `impl Trait` values).

use rustc_index::vec::Idx;
use rustc_infer::infer::LateBoundRegionConversionTime;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
Expand Down Expand Up @@ -83,7 +82,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
}

// In MIR, argument N is stored in local N+1.
let local = Local::new(argument_index + 1);
let local = Local::from_usize(argument_index + 1);

let mir_input_ty = body.local_decls[local].ty;

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_borrowck/src/universal_regions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::lang_items::LangItem;
use rustc_hir::BodyOwnerKind;
use rustc_index::vec::{Idx, IndexVec};
use rustc_index::vec::IndexVec;
use rustc_infer::infer::NllRegionVariableOrigin;
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::{self, InlineConstSubsts, InlineConstSubstsParts, RegionVid, Ty, TyCtxt};
Expand Down Expand Up @@ -289,7 +289,7 @@ impl<'tcx> UniversalRegions<'tcx> {
/// Returns an iterator over all the RegionVids corresponding to
/// universally quantified free regions.
pub fn universal_regions(&self) -> impl Iterator<Item = RegionVid> {
(FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::new)
(FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize)
}

/// Returns `true` if `r` is classified as an local region.
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_codegen_ssa/src/mir/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use crate::MemFlags;
use rustc_ast as ast;
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
use rustc_hir::lang_items::LangItem;
use rustc_index::vec::Idx;
use rustc_middle::mir::{self, AssertKind, SwitchTargets};
use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
Expand Down Expand Up @@ -369,7 +368,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
if self.fn_abi.c_variadic {
// The `VaList` "spoofed" argument is just after all the real arguments.
let va_list_arg_idx = self.fn_abi.args.len();
match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
match self.locals[mir::Local::from_usize(1 + va_list_arg_idx)] {
LocalRef::Place(va_list) => {
bx.va_end(va_list.llval);
}
Expand Down
17 changes: 9 additions & 8 deletions compiler/rustc_const_eval/src/interpret/discriminant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,18 +211,19 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
let variant_index_relative = u32::try_from(variant_index_relative)
.expect("we checked that this fits into a u32");
// Then computing the absolute variant idx should not overflow any more.
let variant_index = variants_start
.checked_add(variant_index_relative)
.expect("overflow computing absolute variant idx");
let variants_len = op
let variant_index = VariantIdx::from_u32(
variants_start
.checked_add(variant_index_relative)
.expect("overflow computing absolute variant idx"),
);
let variants = op
.layout
.ty
.ty_adt_def()
.expect("tagged layout for non adt")
.variants()
.len();
assert!(usize::try_from(variant_index).unwrap() < variants_len);
VariantIdx::from_u32(variant_index)
.variants();
assert!(variant_index < variants.next_index());
variant_index
} else {
untagged_variant
}
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_hir_typeck/src/demand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self, Article, AssocItem, Ty, TypeAndMut, TypeFoldable};
use rustc_span::symbol::{sym, Symbol};
use rustc_span::{BytePos, Span, DUMMY_SP};
use rustc_target::abi::FieldIdx;
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::ObligationCause;

Expand Down Expand Up @@ -875,7 +874,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
variant.fields.len() == 1
})
.filter_map(|variant| {
let sole_field = &variant.fields[FieldIdx::from_u32(0)];
let sole_field = &variant.single_field();

let field_is_local = sole_field.did.is_local();
let field_is_accessible =
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_typeck/src/intrinsicck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use rustc_hir as hir;
use rustc_index::vec::Idx;
use rustc_middle::ty::layout::{LayoutError, SizeSkeleton};
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
use rustc_target::abi::{FieldIdx, Pointer, VariantIdx};
use rustc_target::abi::{Pointer, VariantIdx};

use super::FnCtxt;

Expand All @@ -28,7 +28,7 @@ fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
}

if def.variant(data_idx).fields.len() == 1 {
return def.variant(data_idx).fields[FieldIdx::from_u32(0)].ty(tcx, substs);
return def.variant(data_idx).single_field().ty(tcx, substs);
}
}

Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_infer/src/infer/error_reporting/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use rustc_middle::traits::{
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self as ty, GenericArgKind, IsSuggestable, Ty, TypeVisitableExt};
use rustc_span::{sym, BytePos, Span};
use rustc_target::abi::FieldIdx;

use crate::errors::{
ConsiderAddingAwait, FnConsiderCasting, FnItemsAreDistinct, FnUniqTypes,
Expand Down Expand Up @@ -114,7 +113,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
variant.fields.len() == 1 && variant.ctor_kind() == Some(CtorKind::Fn)
})
.filter_map(|variant| {
let sole_field = &variant.fields[FieldIdx::from_u32(0)];
let sole_field = &variant.single_field();
let sole_field_ty = sole_field.ty(self.tcx, substs);
if self.same_type_modulo_infer(sole_field_ty, exp_found.found) {
let variant_path =
Expand Down
10 changes: 10 additions & 0 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1969,6 +1969,16 @@ impl VariantDef {
pub fn ctor_def_id(&self) -> Option<DefId> {
self.ctor.map(|(_, def_id)| def_id)
}

/// Returns the one field in this variant.
///
/// `panic!`s if there are no fields or multiple fields.
#[inline]
pub fn single_field(&self) -> &FieldDef {
assert!(self.fields.len() == 1);

&self.fields[FieldIdx::from_u32(0)]
}
}

impl PartialEq for VariantDef {
Expand Down
5 changes: 1 addition & 4 deletions compiler/rustc_query_system/src/dep_graph/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ impl<K: DepKind> DepGraphQuery<K> {

pub fn push(&mut self, index: DepNodeIndex, node: DepNode<K>, edges: &[DepNodeIndex]) {
let source = self.graph.add_node(node);
if index.index() >= self.dep_index_to_index.len() {
self.dep_index_to_index.resize(index.index() + 1, None);
}
self.dep_index_to_index[index] = Some(source);
self.dep_index_to_index.insert(index, source);
self.indices.insert(node, source);

for &target in edges.iter() {
Expand Down
13 changes: 7 additions & 6 deletions compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@
use super::{CanonicalGoal, Certainty, EvalCtxt, Goal};
use crate::solve::canonicalize::{CanonicalizeMode, Canonicalizer};
use crate::solve::{CanonicalResponse, QueryResult, Response};
use rustc_index::vec::IndexVec;
use rustc_infer::infer::canonical::query_response::make_query_region_constraints;
use rustc_infer::infer::canonical::CanonicalVarValues;
use rustc_infer::infer::canonical::{CanonicalExt, QueryRegionConstraints};
use rustc_middle::traits::query::NoSolution;
use rustc_middle::traits::solve::{ExternalConstraints, ExternalConstraintsData};
use rustc_middle::ty::{self, GenericArgKind};
use rustc_middle::ty::{self, BoundVar, GenericArgKind};
use rustc_span::DUMMY_SP;
use std::iter;
use std::ops::Deref;
Expand Down Expand Up @@ -139,25 +140,25 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
//
// We therefore instantiate the existential variable in the canonical response with the
// inference variable of the input right away, which is more performant.
let mut opt_values = vec![None; response.variables.len()];
let mut opt_values = IndexVec::from_elem_n(None, response.variables.len());
for (original_value, result_value) in iter::zip(original_values, var_values.var_values) {
match result_value.unpack() {
GenericArgKind::Type(t) => {
if let &ty::Bound(debruijn, b) = t.kind() {
assert_eq!(debruijn, ty::INNERMOST);
opt_values[b.var.index()] = Some(*original_value);
opt_values[b.var] = Some(*original_value);
}
}
GenericArgKind::Lifetime(r) => {
if let ty::ReLateBound(debruijn, br) = *r {
assert_eq!(debruijn, ty::INNERMOST);
opt_values[br.var.index()] = Some(*original_value);
opt_values[br.var] = Some(*original_value);
}
}
GenericArgKind::Const(c) => {
if let ty::ConstKind::Bound(debrujin, b) = c.kind() {
assert_eq!(debrujin, ty::INNERMOST);
opt_values[b.index()] = Some(*original_value);
opt_values[b] = Some(*original_value);
}
}
}
Expand All @@ -180,7 +181,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
// more placeholders then they should be able to. However the inference variables have
// to "come from somewhere", so by equating them with the original values of the caller
// later on, we pull them down into their correct universe again.
if let Some(v) = opt_values[index] {
if let Some(v) = opt_values[BoundVar::from_usize(index)] {
v
} else {
self.infcx.instantiate_canonical_var(DUMMY_SP, info, |_| prev_universe)
Expand Down