Skip to content

Commit

Permalink
Auto merge of rust-lang#132623 - nnethercote:rustc_borrowck-cleanups-…
Browse files Browse the repository at this point in the history
…2, r=<try>

`rustc_borrowck` cleanups, part 2

The code under `do_mir_borrowck` is pretty messy, especially the various types like `MirBorrowckCtxt`, `BorrowckInferCtxt`, `MirTypeckResults`, `MirTypeckRegionConstraints`, `CreateResult`, `TypeChecker`, `TypeVerifier`, `LivenessContext`, `LivenessResults`. This PR does some tidying up, though there's still plenty of mess left afterwards.

A sequel to rust-lang#132250.

r? `@compiler-errors`
  • Loading branch information
bors committed Nov 15, 2024
2 parents 76fd471 + 976ba9e commit 717a575
Show file tree
Hide file tree
Showing 22 changed files with 154 additions and 213 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl<'tcx> UniverseInfo<'tcx> {
UniverseInfo::RelateTys { expected, found } => {
let err = mbcx.infcx.err_ctxt().report_mismatched_types(
&cause,
mbcx.param_env,
mbcx.infcx.param_env,
expected,
found,
TypeError::RegionsPlaceholderMismatch,
Expand Down
17 changes: 9 additions & 8 deletions compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -904,7 +904,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let ty = moved_place.ty(self.body, self.infcx.tcx).ty;
debug!("ty: {:?}, kind: {:?}", ty, ty.kind());

let Some(assign_value) = self.infcx.err_ctxt().ty_kind_suggestion(self.param_env, ty)
let Some(assign_value) = self.infcx.err_ctxt().ty_kind_suggestion(self.infcx.param_env, ty)
else {
return;
};
Expand Down Expand Up @@ -1304,7 +1304,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
pub(crate) fn implements_clone(&self, ty: Ty<'tcx>) -> bool {
let Some(clone_trait_def) = self.infcx.tcx.lang_items().clone_trait() else { return false };
self.infcx
.type_implements_trait(clone_trait_def, [ty], self.param_env)
.type_implements_trait(clone_trait_def, [ty], self.infcx.param_env)
.must_apply_modulo_regions()
}

Expand Down Expand Up @@ -1437,7 +1437,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
let cause = ObligationCause::misc(span, self.mir_def_id());

ocx.register_bound(cause, self.param_env, ty, def_id);
ocx.register_bound(cause, self.infcx.param_env, ty, def_id);
let errors = ocx.select_all_or_error();

// Only emit suggestion if all required predicates are on generic
Expand Down Expand Up @@ -1957,7 +1957,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
&& let ty::Ref(_, inner, _) = rcvr_ty.kind()
&& let inner = inner.peel_refs()
&& (Holds { ty: inner }).visit_ty(local_ty).is_break()
&& let None = self.infcx.type_implements_trait_shallow(clone, inner, self.param_env)
&& let None =
self.infcx.type_implements_trait_shallow(clone, inner, self.infcx.param_env)
{
err.span_label(
span,
Expand Down Expand Up @@ -1989,7 +1990,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let obligation = Obligation::new(
self.infcx.tcx,
ObligationCause::dummy(),
self.param_env,
self.infcx.param_env,
trait_ref,
);
self.infcx.err_ctxt().suggest_derive(
Expand Down Expand Up @@ -3398,7 +3399,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
&& self
.infcx
.type_implements_trait(iter_trait, [return_ty], self.param_env)
.type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
.must_apply_modulo_regions()
{
err.span_suggestion_hidden(
Expand Down Expand Up @@ -3837,11 +3838,11 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if tcx.is_diagnostic_item(sym::deref_method, method_did) {
let deref_target =
tcx.get_diagnostic_item(sym::deref_target).and_then(|deref_target| {
Instance::try_resolve(tcx, self.param_env, deref_target, method_args)
Instance::try_resolve(tcx, self.infcx.param_env, deref_target, method_args)
.transpose()
});
if let Some(Ok(instance)) = deref_target {
let deref_target_ty = instance.ty(tcx, self.param_env);
let deref_target_ty = instance.ty(tcx, self.infcx.param_env);
err.note(format!("borrow occurs due to deref coercion to `{deref_target_ty}`"));
err.span_note(tcx.def_span(instance.def_id()), "deref defined here");
}
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_borrowck/src/diagnostics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -864,7 +864,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {

let kind = call_kind(
self.infcx.tcx,
self.param_env,
self.infcx.param_env,
method_did,
method_args,
*fn_span,
Expand Down Expand Up @@ -1160,7 +1160,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let suggest = match tcx.get_diagnostic_item(sym::IntoIterator) {
Some(def_id) => type_known_to_meet_bound_modulo_regions(
self.infcx,
self.param_env,
self.infcx.param_env,
Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty),
def_id,
),
Expand Down Expand Up @@ -1224,7 +1224,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
BoundRegionConversionTime::FnCall,
tcx.fn_sig(method_did).instantiate(tcx, method_args).input(0),
)
&& self.infcx.can_eq(self.param_env, ty, self_ty)
&& self.infcx.can_eq(self.infcx.param_env, ty, self_ty)
{
err.subdiagnostic(CaptureReasonSuggest::FreshReborrow {
span: move_span.shrink_to_hi(),
Expand Down Expand Up @@ -1258,7 +1258,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if let Some(errors) = self.infcx.type_implements_trait_shallow(
clone_trait,
ty,
self.param_env,
self.infcx.param_env,
) && !has_sugg
{
let msg = match &errors[..] {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1242,7 +1242,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.type_implements_trait_shallow(
clone_trait,
ty.peel_refs(),
self.param_env,
self.infcx.param_env,
)
.as_deref()
{
Expand Down Expand Up @@ -1279,7 +1279,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let obligation = traits::Obligation::new(
self.infcx.tcx,
traits::ObligationCause::dummy(),
self.param_env,
self.infcx.param_env,
trait_ref,
);
self.infcx.err_ctxt().suggest_derive(
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_borrowck/src/diagnostics/region_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -952,7 +952,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {

if let Ok(Some(instance)) = ty::Instance::try_resolve(
tcx,
self.param_env,
self.infcx.param_env,
*fn_did,
self.infcx.resolve_vars_if_possible(args),
) {
Expand Down Expand Up @@ -1091,7 +1091,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
peeled_ty = ref_ty;
count += 1;
}
if !self.infcx.type_is_copy_modulo_regions(self.param_env, peeled_ty) {
if !self.infcx.type_is_copy_modulo_regions(self.infcx.param_env, peeled_ty) {
return;
}

Expand Down Expand Up @@ -1160,7 +1160,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let ocx = ObligationCtxt::new(&self.infcx);
ocx.register_obligations(preds.iter().map(|(pred, span)| {
trace!(?pred);
Obligation::misc(tcx, span, self.mir_def_id(), self.param_env, pred)
Obligation::misc(tcx, span, self.mir_def_id(), self.infcx.param_env, pred)
}));

if ocx.select_all_or_error().is_empty() && count > 0 {
Expand Down
22 changes: 6 additions & 16 deletions compiler/rustc_borrowck/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ fn do_mir_borrowck<'tcx>(
) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
let def = input_body.source.def_id().expect_local();
let infcx = BorrowckInferCtxt::new(tcx, def);
let param_env = tcx.param_env(def);

let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
for var_debug_info in &input_body.var_debug_info {
Expand Down Expand Up @@ -175,8 +174,7 @@ fn do_mir_borrowck<'tcx>(
// will have a lifetime tied to the inference context.
let mut body_owned = input_body.clone();
let mut promoted = input_promoted.to_owned();
let free_regions =
nll::replace_regions_in_mir(&infcx, param_env, &mut body_owned, &mut promoted);
let free_regions = nll::replace_regions_in_mir(&infcx, &mut body_owned, &mut promoted);
let body = &body_owned; // no further changes

// FIXME(-Znext-solver): A bit dubious that we're only registering
Expand All @@ -192,7 +190,7 @@ fn do_mir_borrowck<'tcx>(
.iter_enumerated()
.map(|(idx, body)| (idx, MoveData::gather_moves(body, tcx, |_| true)));

let mut flow_inits = MaybeInitializedPlaces::new(tcx, body, &move_data)
let flow_inits = MaybeInitializedPlaces::new(tcx, body, &move_data)
.iterate_to_fixpoint(tcx, body, Some("borrowck"))
.into_results_cursor(body);

Expand All @@ -213,11 +211,9 @@ fn do_mir_borrowck<'tcx>(
body,
&promoted,
&location_table,
param_env,
&mut flow_inits,
flow_inits,
&move_data,
&borrow_set,
tcx.closure_captures(def),
consumer_options,
);

Expand All @@ -229,11 +225,6 @@ fn do_mir_borrowck<'tcx>(
// information.
nll::dump_annotation(&infcx, body, &regioncx, &opt_closure_req, &opaque_type_values, diags);

// The various `flow_*` structures can be large. We drop `flow_inits` here
// so it doesn't overlap with the others below. This reduces peak memory
// usage significantly on some benchmarks.
drop(flow_inits);

let flow_borrows = Borrows::new(tcx, body, &regioncx, &borrow_set).iterate_to_fixpoint(
tcx,
body,
Expand Down Expand Up @@ -268,7 +259,6 @@ fn do_mir_borrowck<'tcx>(
let promoted_body = &promoted[idx];
let mut promoted_mbcx = MirBorrowckCtxt {
infcx: &infcx,
param_env,
body: promoted_body,
move_data: &move_data,
location_table: &location_table, // no need to create a real one for the promoted, it is not used
Expand Down Expand Up @@ -308,7 +298,6 @@ fn do_mir_borrowck<'tcx>(

let mut mbcx = MirBorrowckCtxt {
infcx: &infcx,
param_env,
body,
move_data: &move_data,
location_table: &location_table,
Expand Down Expand Up @@ -429,12 +418,14 @@ fn do_mir_borrowck<'tcx>(
pub(crate) struct BorrowckInferCtxt<'tcx> {
pub(crate) infcx: InferCtxt<'tcx>,
pub(crate) reg_var_to_origin: RefCell<FxIndexMap<ty::RegionVid, RegionCtxt>>,
pub(crate) param_env: ParamEnv<'tcx>,
}

impl<'tcx> BorrowckInferCtxt<'tcx> {
pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
let infcx = tcx.infer_ctxt().build(TypingMode::analysis_in_body(tcx, def_id));
BorrowckInferCtxt { infcx, reg_var_to_origin: RefCell::new(Default::default()) }
let param_env = tcx.param_env(def_id);
BorrowckInferCtxt { infcx, reg_var_to_origin: RefCell::new(Default::default()), param_env }
}

pub(crate) fn next_region_var<F>(
Expand Down Expand Up @@ -513,7 +504,6 @@ impl<'tcx> Deref for BorrowckInferCtxt<'tcx> {

struct MirBorrowckCtxt<'a, 'infcx, 'tcx> {
infcx: &'infcx BorrowckInferCtxt<'tcx>,
param_env: ParamEnv<'tcx>,
body: &'a Body<'tcx>,
move_data: &'a MoveData<'tcx>,

Expand Down
46 changes: 6 additions & 40 deletions compiler/rustc_borrowck/src/nll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use crate::diagnostics::RegionErrors;
use crate::facts::{AllFacts, AllFactsExt, RustcFacts};
use crate::location::LocationTable;
use crate::region_infer::RegionInferenceContext;
use crate::type_check::{self, MirTypeckRegionConstraints, MirTypeckResults};
use crate::type_check::{self, MirTypeckResults};
use crate::universal_regions::UniversalRegions;
use crate::{BorrowckInferCtxt, polonius, renumber};

Expand All @@ -50,10 +50,9 @@ pub(crate) struct NllOutput<'tcx> {
/// Rewrites the regions in the MIR to use NLL variables, also scraping out the set of universal
/// regions (e.g., region parameters) declared on the function. That set will need to be given to
/// `compute_regions`.
#[instrument(skip(infcx, param_env, body, promoted), level = "debug")]
#[instrument(skip(infcx, body, promoted), level = "debug")]
pub(crate) fn replace_regions_in_mir<'tcx>(
infcx: &BorrowckInferCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
body: &mut Body<'tcx>,
promoted: &mut IndexSlice<Promoted, Body<'tcx>>,
) -> UniversalRegions<'tcx> {
Expand All @@ -62,7 +61,7 @@ pub(crate) fn replace_regions_in_mir<'tcx>(
debug!(?def);

// Compute named region information. This also renumbers the inputs/outputs.
let universal_regions = UniversalRegions::new(infcx, def, param_env);
let universal_regions = UniversalRegions::new(infcx, def);

// Replace all remaining regions with fresh inference variables.
renumber::renumber_mir(infcx, body, promoted);
Expand All @@ -81,11 +80,9 @@ pub(crate) fn compute_regions<'a, 'tcx>(
body: &Body<'tcx>,
promoted: &IndexSlice<Promoted, Body<'tcx>>,
location_table: &LocationTable,
param_env: ty::ParamEnv<'tcx>,
flow_inits: &mut ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
flow_inits: ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
move_data: &MoveData<'tcx>,
borrow_set: &BorrowSet<'tcx>,
upvars: &[&ty::CapturedPlace<'tcx>],
consumer_options: Option<ConsumerOptions>,
) -> NllOutput<'tcx> {
let is_polonius_legacy_enabled = infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled();
Expand All @@ -96,41 +93,27 @@ pub(crate) fn compute_regions<'a, 'tcx>(
let mut all_facts =
(polonius_input || AllFacts::enabled(infcx.tcx)).then_some(AllFacts::default());

let universal_regions = Rc::new(universal_regions);

let elements = Rc::new(DenseLocationMap::new(body));

// Run the MIR type-checker.
let MirTypeckResults { constraints, universal_region_relations, opaque_type_values } =
type_check::type_check(
infcx,
param_env,
body,
promoted,
Rc::clone(&universal_regions),
universal_regions,
location_table,
borrow_set,
&mut all_facts,
flow_inits,
move_data,
Rc::clone(&elements),
upvars,
);

// Create the region inference context, taking ownership of the
// region inference data that was contained in `infcx`, and the
// base constraints generated by the type-check.
let var_origins = infcx.get_region_var_origins();
let MirTypeckRegionConstraints {
placeholder_indices,
placeholder_index_to_region: _,
liveness_constraints,
mut outlives_constraints,
mut member_constraints,
universe_causes,
type_tests,
} = constraints;
let placeholder_indices = Rc::new(placeholder_indices);

// If requested, emit legacy polonius facts.
polonius::emit_facts(
Expand All @@ -140,31 +123,14 @@ pub(crate) fn compute_regions<'a, 'tcx>(
body,
borrow_set,
move_data,
&universal_regions,
&universal_region_relations,
);

if let Some(guar) = universal_regions.tainted_by_errors() {
// Suppress unhelpful extra errors in `infer_opaque_types` by clearing out all
// outlives bounds that we may end up checking.
outlives_constraints = Default::default();
member_constraints = Default::default();

// Also taint the entire scope.
infcx.set_tainted_by_errors(guar);
}

let mut regioncx = RegionInferenceContext::new(
infcx,
var_origins,
universal_regions,
placeholder_indices,
constraints,
universal_region_relations,
outlives_constraints,
member_constraints,
universe_causes,
type_tests,
liveness_constraints,
elements,
);

Expand Down
Loading

0 comments on commit 717a575

Please sign in to comment.