Use LocalDefId for closures more

This commit is contained in:
Cameron Steffen 2022-07-12 09:10:22 -05:00
parent 1202bbaf48
commit cf2433a74f
29 changed files with 164 additions and 171 deletions

View File

@ -6,7 +6,6 @@
struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan,
};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::{walk_block, walk_expr, Visitor};
use rustc_hir::{AsyncGeneratorKind, GeneratorKind};
use rustc_infer::infer::TyCtxtInferExt;
@ -21,6 +20,7 @@
self, subst::Subst, suggest_constraining_type_params, EarlyBinder, PredicateKind, Ty,
};
use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex};
use rustc_span::def_id::LocalDefId;
use rustc_span::hygiene::DesugaringKind;
use rustc_span::symbol::sym;
use rustc_span::{BytePos, Span, Symbol};
@ -2224,7 +2224,7 @@ fn annotate_argument_and_return_for_borrow(
let ty = self.infcx.tcx.type_of(self.mir_def_id());
match ty.kind() {
ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
self.mir_def_id().to_def_id(),
self.mir_def_id(),
self.infcx.tcx.fn_sig(self.mir_def_id()),
),
_ => None,
@ -2268,8 +2268,8 @@ fn annotate_argument_and_return_for_borrow(
// Check if our `target` was captured by a closure.
if let Rvalue::Aggregate(
box AggregateKind::Closure(def_id, substs),
operands,
) = rvalue
ref operands,
) = *rvalue
{
for operand in operands {
let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = operand else {
@ -2293,7 +2293,7 @@ fn annotate_argument_and_return_for_borrow(
// into a place then we should annotate the closure in
// case it ends up being assigned into the return place.
annotated_closure =
self.annotate_fn_sig(*def_id, substs.as_closure().sig());
self.annotate_fn_sig(def_id, substs.as_closure().sig());
debug!(
"annotate_argument_and_return_for_borrow: \
annotated_closure={:?} assigned_from_local={:?} \
@ -2415,12 +2415,12 @@ fn annotate_argument_and_return_for_borrow(
/// references.
fn annotate_fn_sig(
&self,
did: DefId,
did: LocalDefId,
sig: ty::PolyFnSig<'tcx>,
) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
let is_closure = self.infcx.tcx.is_closure(did);
let fn_hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did.as_local()?);
let is_closure = self.infcx.tcx.is_closure(did.to_def_id());
let fn_hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did);
let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
// We need to work out which arguments to highlight. We do this by looking

View File

@ -5,9 +5,9 @@
use rustc_errors::{Applicability, Diagnostic};
use rustc_hir as hir;
use rustc_hir::def::Namespace;
use rustc_hir::def_id::DefId;
use rustc_hir::GeneratorKind;
use rustc_infer::infer::TyCtxtInferExt;
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::{
AggregateKind, Constant, FakeReadCause, Field, Local, LocalInfo, LocalKind, Location, Operand,
Place, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind,
@ -15,6 +15,7 @@
use rustc_middle::ty::print::Print;
use rustc_middle::ty::{self, DefIdTree, Instance, Ty, TyCtxt};
use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult};
use rustc_span::def_id::LocalDefId;
use rustc_span::{symbol::sym, Span, DUMMY_SP};
use rustc_target::abi::VariantIdx;
use rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions;
@ -41,7 +42,6 @@
pub(crate) use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors};
pub(crate) use region_name::{RegionName, RegionNameSource};
pub(crate) use rustc_const_eval::util::CallKind;
use rustc_middle::mir::tcx::PlaceTy;
pub(super) struct IncludingDowncast(pub(super) bool);
@ -325,10 +325,11 @@ fn describe_field_from_ty(
// so it's safe to call `expect_local`.
//
// We know the field exists so it's safe to call operator[] and `unwrap` here.
let def_id = def_id.expect_local();
let var_id = self
.infcx
.tcx
.typeck(def_id.expect_local())
.typeck(def_id)
.closure_min_captures_flattened(def_id)
.nth(field.index())
.unwrap()
@ -715,12 +716,11 @@ pub(super) fn move_spans(
debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
if let StatementKind::Assign(box (_, Rvalue::Aggregate(ref kind, ref places))) = stmt.kind {
match kind {
box AggregateKind::Closure(def_id, _)
| box AggregateKind::Generator(def_id, _, _) => {
match **kind {
AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
debug!("move_spans: def_id={:?} places={:?}", def_id, places);
if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
self.closure_span(*def_id, moved_place, places)
self.closure_span(def_id, moved_place, places)
{
return ClosureUse {
generator_kind,
@ -847,7 +847,7 @@ pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpan
if let StatementKind::Assign(box (_, Rvalue::Aggregate(ref kind, ref places))) =
stmt.kind
{
let (def_id, is_generator) = match kind {
let (&def_id, is_generator) = match kind {
box AggregateKind::Closure(def_id, _) => (def_id, false),
box AggregateKind::Generator(def_id, _, _) => (def_id, true),
_ => continue,
@ -858,7 +858,7 @@ pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpan
def_id, is_generator, places
);
if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
self.closure_span(*def_id, Place::from(target).as_ref(), places)
self.closure_span(def_id, Place::from(target).as_ref(), places)
{
return ClosureUse { generator_kind, args_span, capture_kind_span, path_span };
} else {
@ -879,7 +879,7 @@ pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpan
/// The second span is the location the use resulting in the captured path of the capture
fn closure_span(
&self,
def_id: DefId,
def_id: LocalDefId,
target_place: PlaceRef<'tcx>,
places: &[Operand<'tcx>],
) -> Option<(Span, Option<GeneratorKind>, Span, Span)> {
@ -887,17 +887,12 @@ fn closure_span(
"closure_span: def_id={:?} target_place={:?} places={:?}",
def_id, target_place, places
);
let local_did = def_id.as_local()?;
let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(local_did);
let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(def_id);
let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind;
debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
if let hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, .. }) = expr {
for (captured_place, place) in self
.infcx
.tcx
.typeck(def_id.expect_local())
.closure_min_captures_flattened(def_id)
.zip(places)
for (captured_place, place) in
self.infcx.tcx.typeck(def_id).closure_min_captures_flattened(def_id).zip(places)
{
match place {
Operand::Copy(place) | Operand::Move(place)

View File

@ -343,7 +343,7 @@ pub(crate) fn report_mutability_error(
);
let tcx = self.infcx.tcx;
if let ty::Closure(id, _) = *the_place_err.ty(self.body, tcx).ty.kind() {
self.show_mutating_upvar(tcx, id, the_place_err, &mut err);
self.show_mutating_upvar(tcx, id.expect_local(), the_place_err, &mut err);
}
}
@ -382,7 +382,7 @@ pub(crate) fn report_mutability_error(
if let ty::Ref(_, ty, Mutability::Mut) = the_place_err.ty(self.body, tcx).ty.kind()
&& let ty::Closure(id, _) = *ty.kind()
{
self.show_mutating_upvar(tcx, id, the_place_err, &mut err);
self.show_mutating_upvar(tcx, id.expect_local(), the_place_err, &mut err);
}
}
@ -685,11 +685,10 @@ fn is_error_in_trait(&self, local: Local) -> (bool, Option<Span>) {
fn show_mutating_upvar(
&self,
tcx: TyCtxt<'_>,
id: hir::def_id::DefId,
closure_local_def_id: hir::def_id::LocalDefId,
the_place_err: PlaceRef<'tcx>,
err: &mut Diagnostic,
) {
let closure_local_def_id = id.expect_local();
let tables = tcx.typeck(closure_local_def_id);
let closure_hir_id = tcx.hir().local_def_id_to_hir_id(closure_local_def_id);
if let Some((span, closure_kind_origin)) =
@ -699,7 +698,8 @@ fn show_mutating_upvar(
let upvar = ty::place_to_string_for_capture(tcx, closure_kind_origin);
let root_hir_id = upvar_id.var_path.hir_id;
// we have an origin for this closure kind starting at this root variable so it's safe to unwrap here
let captured_places = tables.closure_min_captures[&id].get(&root_hir_id).unwrap();
let captured_places =
tables.closure_min_captures[&closure_local_def_id].get(&root_hir_id).unwrap();
let origin_projection = closure_kind_origin
.projections

View File

@ -189,7 +189,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
pub(crate) fn mir_def_id(&self) -> hir::def_id::LocalDefId {
self.body.source.def_id().as_local().unwrap()
self.body.source.def_id().expect_local()
}
pub(crate) fn mir_hir_id(&self) -> hir::HirId {

View File

@ -189,7 +189,7 @@ fn do_mir_borrowck<'a, 'tcx>(
errors.set_tainted_by_errors();
}
let upvars: Vec<_> = tables
.closure_min_captures_flattened(def.did.to_def_id())
.closure_min_captures_flattened(def.did)
.map(|captured_place| {
let capture = captured_place.info.capture_kind;
let by_ref = match capture {
@ -1295,7 +1295,7 @@ fn consume_rvalue(
match **aggregate_kind {
AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
let BorrowCheckResult { used_mut_upvars, .. } =
self.infcx.tcx.mir_borrowck(def_id.expect_local());
self.infcx.tcx.mir_borrowck(def_id);
debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
for field in used_mut_upvars {
self.propagate_closure_used_mut_upvar(&operands[field.index()]);

View File

@ -1847,14 +1847,11 @@ fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
let tcx = self.tcx();
let def_id = uv.def.def_id_for_type_of();
if tcx.def_kind(def_id) == DefKind::InlineConst {
let predicates = self.prove_closure_bounds(
tcx,
def_id.expect_local(),
uv.substs,
location,
);
let def_id = def_id.expect_local();
let predicates =
self.prove_closure_bounds(tcx, def_id, uv.substs, location);
self.normalize_and_prove_instantiated_predicates(
def_id,
def_id.to_def_id(),
predicates,
location.to_locations(),
);
@ -2514,9 +2511,9 @@ fn prove_aggregate_predicates(
aggregate_kind, location
);
let (def_id, instantiated_predicates) = match aggregate_kind {
let (def_id, instantiated_predicates) = match *aggregate_kind {
AggregateKind::Adt(adt_did, _, substs, _, _) => {
(*adt_did, tcx.predicates_of(*adt_did).instantiate(tcx, substs))
(adt_did, tcx.predicates_of(adt_did).instantiate(tcx, substs))
}
// For closures, we have some **extra requirements** we
@ -2541,7 +2538,7 @@ fn prove_aggregate_predicates(
// clauses on the struct.
AggregateKind::Closure(def_id, substs)
| AggregateKind::Generator(def_id, substs, _) => {
(*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location))
(def_id.to_def_id(), self.prove_closure_bounds(tcx, def_id, substs, location))
}
AggregateKind::Array(_) | AggregateKind::Tuple => {

View File

@ -238,7 +238,7 @@ fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize)
if let Some(local_def_id) = def_id.as_local() {
let tables = self.ecx.tcx.typeck(local_def_id);
if let Some(captured_place) =
tables.closure_min_captures_flattened(*def_id).nth(field)
tables.closure_min_captures_flattened(local_def_id).nth(field)
{
// Sometimes the index is beyond the number of upvars (seen
// for a generator).

View File

@ -1983,53 +1983,45 @@ fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
}
AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
if let Some(def_id) = def_id.as_local() {
let name = if tcx.sess.opts.unstable_opts.span_free_formats {
let substs = tcx.lift(substs).unwrap();
format!(
"[closure@{}]",
tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
)
} else {
let span = tcx.def_span(def_id);
format!(
"[closure@{}]",
tcx.sess.source_map().span_to_diagnostic_string(span)
)
};
let mut struct_fmt = fmt.debug_struct(&name);
// FIXME(project-rfc-2229#48): This should be a list of capture names/places
if let Some(upvars) = tcx.upvars_mentioned(def_id) {
for (&var_id, place) in iter::zip(upvars.keys(), places) {
let var_name = tcx.hir().name(var_id);
struct_fmt.field(var_name.as_str(), place);
}
}
struct_fmt.finish()
let name = if tcx.sess.opts.unstable_opts.span_free_formats {
let substs = tcx.lift(substs).unwrap();
format!(
"[closure@{}]",
tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
)
} else {
write!(fmt, "[closure]")
let span = tcx.def_span(def_id);
format!(
"[closure@{}]",
tcx.sess.source_map().span_to_diagnostic_string(span)
)
};
let mut struct_fmt = fmt.debug_struct(&name);
// FIXME(project-rfc-2229#48): This should be a list of capture names/places
if let Some(upvars) = tcx.upvars_mentioned(def_id) {
for (&var_id, place) in iter::zip(upvars.keys(), places) {
let var_name = tcx.hir().name(var_id);
struct_fmt.field(var_name.as_str(), place);
}
}
struct_fmt.finish()
}),
AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
if let Some(def_id) = def_id.as_local() {
let name = format!("[generator@{:?}]", tcx.def_span(def_id));
let mut struct_fmt = fmt.debug_struct(&name);
let name = format!("[generator@{:?}]", tcx.def_span(def_id));
let mut struct_fmt = fmt.debug_struct(&name);
// FIXME(project-rfc-2229#48): This should be a list of capture names/places
if let Some(upvars) = tcx.upvars_mentioned(def_id) {
for (&var_id, place) in iter::zip(upvars.keys(), places) {
let var_name = tcx.hir().name(var_id);
struct_fmt.field(var_name.as_str(), place);
}
// FIXME(project-rfc-2229#48): This should be a list of capture names/places
if let Some(upvars) = tcx.upvars_mentioned(def_id) {
for (&var_id, place) in iter::zip(upvars.keys(), places) {
let var_name = tcx.hir().name(var_id);
struct_fmt.field(var_name.as_str(), place);
}
struct_fmt.finish()
} else {
write!(fmt, "[generator]")
}
struct_fmt.finish()
}),
}
}

View File

@ -18,6 +18,7 @@
use rustc_target::abi::VariantIdx;
use rustc_ast::Mutability;
use rustc_span::def_id::LocalDefId;
use rustc_span::symbol::Symbol;
use rustc_span::Span;
use rustc_target::asm::InlineAsmRegOrRegClass;
@ -340,8 +341,11 @@ pub enum FakeReadCause {
/// If a closure pattern matches a Place starting with an Upvar, then we introduce a
/// FakeRead for that Place outside the closure, in such a case this option would be
/// Some(closure_def_id).
/// Otherwise, the value of the optional DefId will be None.
ForMatchedPlace(Option<DefId>),
/// Otherwise, the value of the optional LocalDefId will be None.
//
// We can use LocaDefId here since fake read statements are removed
// before codegen in the `CleanupNonCodegenStatements` pass.
ForMatchedPlace(Option<LocalDefId>),
/// A fake read of the RefWithinGuard version of a bind-by-value variable
/// in a match guard to ensure that its value hasn't change by the time
@ -365,7 +369,7 @@ pub enum FakeReadCause {
/// FakeRead for that Place outside the closure, in such a case this option would be
/// Some(closure_def_id).
/// Otherwise, the value of the optional DefId will be None.
ForLet(Option<DefId>),
ForLet(Option<LocalDefId>),
/// If we have an index expression like
///
@ -1095,8 +1099,10 @@ pub enum AggregateKind<'tcx> {
/// active field index would identity the field `c`
Adt(DefId, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
Closure(DefId, SubstsRef<'tcx>),
Generator(DefId, SubstsRef<'tcx>, hir::Movability),
// Note: We can use LocalDefId since closures and generators a deaggregated
// before codegen.
Closure(LocalDefId, SubstsRef<'tcx>),
Generator(LocalDefId, SubstsRef<'tcx>, hir::Movability),
}
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]

View File

@ -205,9 +205,9 @@ pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
AggregateKind::Adt(did, _, substs, _, _) => {
tcx.bound_type_of(did).subst(tcx, substs)
}
AggregateKind::Closure(did, substs) => tcx.mk_closure(did, substs),
AggregateKind::Closure(did, substs) => tcx.mk_closure(did.to_def_id(), substs),
AggregateKind::Generator(did, substs, movability) => {
tcx.mk_generator(did, substs, movability)
tcx.mk_generator(did.to_def_id(), substs, movability)
}
},
Rvalue::ShallowInitBox(_, ty) => tcx.mk_box(ty),

View File

@ -413,12 +413,12 @@
}
query symbols_for_closure_captures(
key: (LocalDefId, DefId)
key: (LocalDefId, LocalDefId)
) -> Vec<rustc_span::Symbol> {
storage(ArenaCacheSelector<'tcx>)
desc {
|tcx| "symbols for captures of closure `{}` in `{}`",
tcx.def_path_str(key.1),
tcx.def_path_str(key.1.to_def_id()),
tcx.def_path_str(key.0.to_def_id())
}
}

View File

@ -27,6 +27,7 @@
use rustc_target::abi::VariantIdx;
use rustc_target::asm::InlineAsmRegOrRegClass;
use rustc_span::def_id::LocalDefId;
use std::fmt;
use std::ops::Index;
@ -405,7 +406,7 @@ pub enum ExprKind<'tcx> {
},
/// A closure definition.
Closure {
closure_id: DefId,
closure_id: LocalDefId,
substs: UpvarSubsts<'tcx>,
upvars: Box<[ExprId]>,
movability: Option<hir::Movability>,

View File

@ -59,7 +59,7 @@ pub enum UpvarCapture {
/// Given the closure DefId this map provides a map of root variables to minimum
/// set of `CapturedPlace`s that need to be tracked to support all captures of that closure.
pub type MinCaptureInformationMap<'tcx> = FxHashMap<DefId, RootVariableMinCaptureList<'tcx>>;
pub type MinCaptureInformationMap<'tcx> = FxHashMap<LocalDefId, RootVariableMinCaptureList<'tcx>>;
/// Part of `MinCaptureInformationMap`; Maps a root variable to the list of `CapturedPlace`.
/// Used to track the minimum set of `Place`s that need to be captured to support all
@ -253,7 +253,7 @@ pub fn get_capture_kind_span(&self, tcx: TyCtxt<'tcx>) -> Span {
fn symbols_for_closure_captures<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: (LocalDefId, DefId),
def_id: (LocalDefId, LocalDefId),
) -> Vec<Symbol> {
let typeck_results = tcx.typeck(def_id.0);
let captures = typeck_results.closure_min_captures_flattened(def_id.1);

View File

@ -570,7 +570,7 @@ pub struct TypeckResults<'tcx> {
/// we never capture `t`. This becomes an issue when we build MIR as we require
/// information on `t` in order to create place `t.0` and `t.1`. We can solve this
/// issue by fake reading `t`.
pub closure_fake_reads: FxHashMap<DefId, Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>>,
pub closure_fake_reads: FxHashMap<LocalDefId, Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>>,
/// Tracks the rvalue scoping rules which defines finer scoping for rvalue expressions
/// by applying extended parameter rules.
@ -589,7 +589,7 @@ pub struct TypeckResults<'tcx> {
/// Contains the data for evaluating the effect of feature `capture_disjoint_fields`
/// on closure size.
pub closure_size_eval: FxHashMap<DefId, ClosureSizeProfileData<'tcx>>,
pub closure_size_eval: FxHashMap<LocalDefId, ClosureSizeProfileData<'tcx>>,
}
impl<'tcx> TypeckResults<'tcx> {
@ -811,7 +811,7 @@ pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>
/// by the closure.
pub fn closure_min_captures_flattened(
&self,
closure_def_id: DefId,
closure_def_id: LocalDefId,
) -> impl Iterator<Item = &ty::CapturedPlace<'tcx>> {
self.closure_min_captures
.get(&closure_def_id)

View File

@ -3,7 +3,7 @@
use crate::build::expr::category::Category;
use crate::build::ForGuard::{OutsideGuard, RefWithinGuard};
use crate::build::{BlockAnd, BlockAndExtension, Builder};
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::def_id::LocalDefId;
use rustc_middle::hir::place::Projection as HirProjection;
use rustc_middle::hir::place::ProjectionKind as HirProjectionKind;
use rustc_middle::middle::region;
@ -58,7 +58,7 @@ pub(crate) enum PlaceBase {
/// HirId of the upvar
var_hir_id: LocalVarId,
/// DefId of the closure
closure_def_id: DefId,
closure_def_id: LocalDefId,
/// The trait closure implements, `Fn`, `FnMut`, `FnOnce`
closure_kind: ty::ClosureKind,
},
@ -176,7 +176,7 @@ fn compute_capture_idx<'tcx>(
fn find_capture_matching_projections<'a, 'tcx>(
typeck_results: &'a ty::TypeckResults<'tcx>,
var_hir_id: LocalVarId,
closure_def_id: DefId,
closure_def_id: LocalDefId,
projections: &[PlaceElem<'tcx>],
) -> Option<(usize, &'a ty::CapturedPlace<'tcx>)> {
let closure_min_captures = typeck_results.closure_min_captures.get(&closure_def_id)?;
@ -242,7 +242,7 @@ fn to_upvars_resolved_place_builder<'a, 'tcx>(
};
// We won't be building MIR if the closure wasn't local
let closure_hir_id = tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local());
let closure_hir_id = tcx.hir().local_def_id_to_hir_id(closure_def_id);
let closure_ty = typeck_results.node_type(closure_hir_id);
let substs = match closure_ty.kind() {
@ -626,11 +626,11 @@ fn expr_as_place(
fn lower_captured_upvar(
&mut self,
block: BasicBlock,
closure_expr_id: LocalDefId,
closure_def_id: LocalDefId,
var_hir_id: LocalVarId,
) -> BlockAnd<PlaceBuilder<'tcx>> {
let closure_ty =
self.typeck_results.node_type(self.tcx.hir().local_def_id_to_hir_id(closure_expr_id));
self.typeck_results.node_type(self.tcx.hir().local_def_id_to_hir_id(closure_def_id));
let closure_kind = if let ty::Closure(_, closure_substs) = closure_ty.kind() {
self.infcx.closure_kind(closure_substs).unwrap()
@ -639,11 +639,7 @@ fn lower_captured_upvar(
ty::ClosureKind::FnOnce
};
block.and(PlaceBuilder::from(PlaceBase::Upvar {
var_hir_id,
closure_def_id: closure_expr_id.to_def_id(),
closure_kind,
}))
block.and(PlaceBuilder::from(PlaceBase::Upvar { var_hir_id, closure_def_id, closure_kind }))
}
/// Lower an index expression

View File

@ -672,7 +672,7 @@ fn construct_fn<'tcx, A>(
Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
builder.args_and_body(
START_BLOCK,
fn_def.did.to_def_id(),
fn_def.did,
&arguments,
arg_scope,
&thir[expr],
@ -895,7 +895,7 @@ fn finish(self) -> Body<'tcx> {
fn args_and_body(
&mut self,
mut block: BasicBlock,
fn_def_id: DefId,
fn_def_id: LocalDefId,
arguments: &[ArgInfo<'tcx>],
argument_scope: region::Scope,
expr: &Expr<'tcx>,

View File

@ -408,7 +408,6 @@ fn visit_expr(&mut self, expr: &Expr<'tcx>) {
movability: _,
fake_reads: _,
} => {
let closure_id = closure_id.expect_local();
let closure_def = if let Some((did, const_param_id)) =
ty::WithOptConstParam::try_lookup(closure_id, self.tcx)
{

View File

@ -523,6 +523,7 @@ fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx>
span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
}
};
let def_id = def_id.expect_local();
let upvars = self
.typeck_results

View File

@ -129,7 +129,7 @@ fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
}
&AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
self.tcx.unsafety_check_result(def_id.expect_local());
self.tcx.unsafety_check_result(def_id);
self.register_violations(
violations,
used_unsafe_blocks.iter().map(|(&h, &d)| (h, d)),

View File

@ -17,8 +17,8 @@ pub(crate) fn dump_closure_profile<'tcx>(tcx: TyCtxt<'tcx>, closure_instance: In
return;
};
let closure_def_id = closure_instance.def_id();
let typeck_results = tcx.typeck(closure_def_id.expect_local());
let closure_def_id = closure_instance.def_id().expect_local();
let typeck_results = tcx.typeck(closure_def_id);
if typeck_results.closure_size_eval.contains_key(&closure_def_id) {
let param_env = ty::ParamEnv::reveal_all();

View File

@ -519,7 +519,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
fn new(ir: &'a mut IrMaps<'tcx>, body_owner: LocalDefId) -> Liveness<'a, 'tcx> {
let typeck_results = ir.tcx.typeck(body_owner);
let param_env = ir.tcx.param_env(body_owner);
let closure_min_captures = typeck_results.closure_min_captures.get(&body_owner.to_def_id());
let closure_min_captures = typeck_results.closure_min_captures.get(&body_owner);
let closure_ln = ir.add_live_node(ClosureNode);
let exit_ln = ir.add_live_node(ExitNode);

View File

@ -191,6 +191,16 @@ fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
}
}
impl Key for (LocalDefId, LocalDefId) {
#[inline(always)]
fn query_crate_is_local(&self) -> bool {
true
}
fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
self.0.default_span(tcx)
}
}
impl Key for (DefId, Option<Ident>) {
#[inline(always)]
fn query_crate_is_local(&self) -> bool {

View File

@ -5,7 +5,7 @@
use rustc_errors::{struct_span_err, Applicability, Diagnostic};
use rustc_hir as hir;
use rustc_hir::def::{self, Namespace, Res};
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_hir::def_id::DefId;
use rustc_infer::{
infer,
traits::{self, Obligation},
@ -19,11 +19,13 @@
};
use rustc_middle::ty::subst::{Subst, SubstsRef};
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable};
use rustc_span::def_id::LocalDefId;
use rustc_span::symbol::{sym, Ident};
use rustc_span::Span;
use rustc_target::spec::abi;
use rustc_trait_selection::autoderef::Autoderef;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
use std::iter;
/// Checks that it is legal to call methods of the trait corresponding
@ -59,7 +61,7 @@ pub fn check_legal_trait_for_method_call(
enum CallStep<'tcx> {
Builtin(Ty<'tcx>),
DeferredClosure(DefId, ty::FnSig<'tcx>),
DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
/// E.g., enum variant constructors.
Overloaded(MethodCallee<'tcx>),
}
@ -145,7 +147,7 @@ fn try_overloaded_call_step(
}
ty::Closure(def_id, substs) => {
assert_eq!(def_id.krate, LOCAL_CRATE);
let def_id = def_id.expect_local();
// Check whether this is a call to a closure where we
// haven't yet decided on whether the closure is fn vs
@ -558,7 +560,7 @@ fn confirm_deferred_closure_call(
call_expr: &'tcx hir::Expr<'tcx>,
arg_exprs: &'tcx [hir::Expr<'tcx>],
expected: Expectation<'tcx>,
closure_def_id: DefId,
closure_def_id: LocalDefId,
fn_sig: ty::FnSig<'tcx>,
) -> Ty<'tcx> {
// `fn_sig` is the *signature* of the closure being called. We
@ -581,7 +583,7 @@ fn confirm_deferred_closure_call(
arg_exprs,
fn_sig.c_variadic,
TupleArgumentsFlag::TupleArguments,
Some(closure_def_id),
Some(closure_def_id.to_def_id()),
);
fn_sig.output()

View File

@ -29,6 +29,7 @@
ToPredicate, Ty, UserType,
};
use rustc_session::lint;
use rustc_span::def_id::LocalDefId;
use rustc_span::hygiene::DesugaringKind;
use rustc_span::symbol::{kw, sym, Ident};
use rustc_span::{Span, DUMMY_SP};
@ -114,7 +115,7 @@ pub(in super::super) fn resolve_vars_with_obligations_and_mutate_fulfillment(
pub(in super::super) fn record_deferred_call_resolution(
&self,
closure_def_id: DefId,
closure_def_id: LocalDefId,
r: DeferredCallResolution<'tcx>,
) {
let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
@ -123,7 +124,7 @@ pub(in super::super) fn record_deferred_call_resolution(
pub(in super::super) fn remove_deferred_call_resolutions(
&self,
closure_def_id: DefId,
closure_def_id: LocalDefId,
) -> Vec<DeferredCallResolution<'tcx>> {
let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default()

View File

@ -2,13 +2,14 @@
use rustc_data_structures::fx::FxHashSet;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::def_id::LocalDefId;
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::visit::TypeVisitable;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::def_id::LocalDefIdMap;
use rustc_span::{self, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
@ -46,7 +47,7 @@ pub struct Inherited<'a, 'tcx> {
// decision. We keep these deferred resolutions grouped by the
// def-id of the closure, so that once we decide, we can easily go
// back and process them.
pub(super) deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
pub(super) deferred_call_resolutions: RefCell<LocalDefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,

View File

@ -35,7 +35,6 @@
use crate::expr_use_visitor as euv;
use rustc_errors::{Applicability, MultiSpan};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::LocalDefId;
use rustc_hir::intravisit::{self, Visitor};
use rustc_infer::infer::UpvarRegion;
@ -186,6 +185,7 @@ fn analyze_closure(
);
}
};
let closure_def_id = closure_def_id.expect_local();
let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
self.closure_kind(closure_substs).is_none().then_some(closure_substs)
@ -193,20 +193,17 @@ fn analyze_closure(
None
};
let local_def_id = closure_def_id.expect_local();
let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
assert_eq!(self.tcx.hir().body_owner_def_id(body.id()), closure_def_id);
let mut delegate = InferBorrowKind {
fcx: self,
closure_def_id: local_def_id,
closure_def_id,
capture_information: Default::default(),
fake_reads: Default::default(),
};
euv::ExprUseVisitor::new(
&mut delegate,
&self.infcx,
body_owner_def_id,
closure_def_id,
self.param_env,
&self.typeck_results.borrow(),
)
@ -224,7 +221,7 @@ fn analyze_closure(
self.compute_min_captures(closure_def_id, capture_information, span);
let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_def_id);
if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
self.perform_2229_migration_anaysis(closure_def_id, body_id, capture_clause, span);
@ -239,7 +236,7 @@ fn analyze_closure(
if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
for var_hir_id in upvars.keys() {
let place = self.place_for_root_variable(local_def_id, *var_hir_id);
let place = self.place_for_root_variable(closure_def_id, *var_hir_id);
debug!("seed place {:?}", place);
@ -333,7 +330,7 @@ fn analyze_closure(
}
// Returns a list of `Ty`s for each upvar.
fn final_upvar_tys(&self, closure_id: DefId) -> Vec<Ty<'tcx>> {
fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
self.typeck_results
.borrow()
.closure_min_captures_flattened(closure_id)
@ -511,7 +508,7 @@ fn process_collected_capture_information(
/// ```
fn compute_min_captures(
&self,
closure_def_id: DefId,
closure_def_id: LocalDefId,
capture_information: InferredCaptureInformation<'tcx>,
closure_span: Span,
) {
@ -730,7 +727,7 @@ fn compute_min_captures(
/// `disjoint_capture_drop_reorder` if needed.
fn perform_2229_migration_anaysis(
&self,
closure_def_id: DefId,
closure_def_id: LocalDefId,
body_id: hir::BodyId,
capture_clause: hir::CaptureBy,
span: Span,
@ -746,8 +743,7 @@ fn perform_2229_migration_anaysis(
let (migration_string, migrated_variables_concat) =
migration_suggestion_for_2229(self.tcx, &need_migrations);
let closure_hir_id =
self.tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local());
let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_def_id);
let closure_head_span = self.tcx.def_span(closure_def_id);
self.tcx.struct_span_lint_hir(
lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
@ -1058,7 +1054,7 @@ fn compute_2229_migrations_for_trait(
#[instrument(level = "debug", skip(self))]
fn compute_2229_migrations_for_drop(
&self,
closure_def_id: DefId,
closure_def_id: LocalDefId,
closure_span: Span,
min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
closure_clause: hir::CaptureBy,
@ -1066,7 +1062,7 @@ fn compute_2229_migrations_for_drop(
) -> Option<FxHashSet<UpvarMigrationInfo>> {
let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
if !ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local())) {
if !ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id)) {
debug!("does not have significant drop");
return None;
}
@ -1160,7 +1156,7 @@ fn compute_2229_migrations_for_drop(
#[instrument(level = "debug", skip(self))]
fn compute_2229_migrations(
&self,
closure_def_id: DefId,
closure_def_id: LocalDefId,
closure_span: Span,
closure_clause: hir::CaptureBy,
min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
@ -1343,14 +1339,13 @@ fn compute_2229_migrations(
/// implements Drop which will be affected since `y` isn't completely captured.
fn has_significant_drop_outside_of_captures(
&self,
closure_def_id: DefId,
closure_def_id: LocalDefId,
closure_span: Span,
base_path_ty: Ty<'tcx>,
captured_by_move_projs: Vec<&[Projection<'tcx>]>,
) -> bool {
let needs_drop = |ty: Ty<'tcx>| {
ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local()))
};
let needs_drop =
|ty: Ty<'tcx>| ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id));
let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
@ -1360,7 +1355,7 @@ fn has_significant_drop_outside_of_captures(
drop_trait,
ty,
ty_params,
self.tcx.param_env(closure_def_id.expect_local()),
self.tcx.param_env(closure_def_id),
)
.must_apply_modulo_regions()
};
@ -1518,13 +1513,13 @@ fn place_for_root_variable(
}
}
fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
self.tcx.has_attr(closure_def_id.to_def_id(), sym::rustc_capture_analysis)
}
fn log_capture_analysis_first_pass(
&self,
closure_def_id: rustc_hir::def_id::DefId,
closure_def_id: LocalDefId,
capture_information: &InferredCaptureInformation<'tcx>,
closure_span: Span,
) {
@ -1543,7 +1538,7 @@ fn log_capture_analysis_first_pass(
}
}
fn log_closure_min_capture_info(&self, closure_def_id: DefId, closure_span: Span) {
fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
if self.should_log_capture_analysis(closure_def_id) {
if let Some(min_captures) =
self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)

View File

@ -8,7 +8,6 @@
use rustc_data_structures::fx::FxHashMap;
use rustc_errors::ErrorGuaranteed;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::{self, Visitor};
use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
use rustc_infer::infer::InferCtxt;
@ -348,14 +347,13 @@ fn visit_infer(&mut self, inf: &'tcx hir::InferArg) {
impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
fn eval_closure_size(&mut self) {
let mut res: FxHashMap<DefId, ClosureSizeProfileData<'tcx>> = Default::default();
for (closure_def_id, data) in self.fcx.typeck_results.borrow().closure_size_eval.iter() {
let closure_hir_id =
self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local());
let mut res: FxHashMap<LocalDefId, ClosureSizeProfileData<'tcx>> = Default::default();
for (&closure_def_id, data) in self.fcx.typeck_results.borrow().closure_size_eval.iter() {
let closure_hir_id = self.tcx().hir().local_def_id_to_hir_id(closure_def_id);
let data = self.resolve(*data, &closure_hir_id);
res.insert(*closure_def_id, data);
res.insert(closure_def_id, data);
}
self.typeck_results.closure_size_eval = res;
@ -365,7 +363,7 @@ fn visit_min_capture_map(&mut self) {
self.fcx.typeck_results.borrow().closure_min_captures.len(),
Default::default(),
);
for (closure_def_id, root_min_captures) in
for (&closure_def_id, root_min_captures) in
self.fcx.typeck_results.borrow().closure_min_captures.iter()
{
let mut root_var_map_wb = ty::RootVariableMinCaptureList::with_capacity_and_hasher(
@ -377,7 +375,7 @@ fn visit_min_capture_map(&mut self) {
.iter()
.map(|captured_place| {
let locatable = captured_place.info.path_expr_id.unwrap_or_else(|| {
self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local())
self.tcx().hir().local_def_id_to_hir_id(closure_def_id)
});
self.resolve(captured_place.clone(), &locatable)
@ -385,7 +383,7 @@ fn visit_min_capture_map(&mut self) {
.collect();
root_var_map_wb.insert(*var_hir_id, min_list_wb);
}
min_captures_wb.insert(*closure_def_id, root_var_map_wb);
min_captures_wb.insert(closure_def_id, root_var_map_wb);
}
self.typeck_results.closure_min_captures = min_captures_wb;
@ -393,21 +391,20 @@ fn visit_min_capture_map(&mut self) {
fn visit_fake_reads_map(&mut self) {
let mut resolved_closure_fake_reads: FxHashMap<
DefId,
LocalDefId,
Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>,
> = Default::default();
for (closure_def_id, fake_reads) in
for (&closure_def_id, fake_reads) in
self.fcx.typeck_results.borrow().closure_fake_reads.iter()
{
let mut resolved_fake_reads = Vec::<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>::new();
for (place, cause, hir_id) in fake_reads.iter() {
let locatable =
self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local());
let locatable = self.tcx().hir().local_def_id_to_hir_id(closure_def_id);
let resolved_fake_read = self.resolve(place.clone(), &locatable);
resolved_fake_reads.push((resolved_fake_read, *cause, *hir_id));
}
resolved_closure_fake_reads.insert(*closure_def_id, resolved_fake_reads);
resolved_closure_fake_reads.insert(closure_def_id, resolved_fake_reads);
}
self.typeck_results.closure_fake_reads = resolved_closure_fake_reads;
}

View File

@ -468,7 +468,7 @@ fn maybe_read_scrutinee<'t>(
self.borrow_expr(discr, ty::ImmBorrow);
} else {
let closure_def_id = match discr_place.place.base {
PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
_ => None,
};
@ -642,7 +642,7 @@ fn walk_autoref(
fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
let closure_def_id = match discr_place.place.base {
PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
_ => None,
};
@ -666,7 +666,7 @@ fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
/// let binding, and *not* a match arm or nested pat.)
fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
let closure_def_id = match discr_place.place.base {
PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
_ => None,
};
@ -763,7 +763,7 @@ fn upvar_is_local_variable<'tcx>(
debug!("walk_captures({:?})", closure_expr);
let tcx = self.tcx();
let closure_def_id = tcx.hir().local_def_id(closure_expr.hir_id).to_def_id();
let closure_def_id = tcx.hir().local_def_id(closure_expr.hir_id);
let upvars = tcx.upvars_mentioned(self.body_owner);
// For purposes of this function, generator and closures are equivalent.

View File

@ -968,7 +968,7 @@ fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
}
},
ExprKind::Closure { .. } => {
let closure_id = self.cx.tcx.hir().local_def_id(e.hir_id).to_def_id();
let closure_id = self.cx.tcx.hir().local_def_id(e.hir_id);
for capture in self.cx.typeck_results().closure_min_captures_flattened(closure_id) {
let local_id = match capture.place.base {
PlaceBase::Local(id) => id,