Skip to content

Commit 43c22af

Browse files
committed
Auto merge of #101632 - camsteffen:refactor-infer-err, r=lcnr
Remove `TypeckResults` from `InferCtxt` `InferCtxt` currently has `in_progress_typeck_results` which is only used for some diagnostics during typeck. It adds a lifetime which propagates through a lot of code. This PR moves that field into a new helper struct `TypeErrCtxt`.
2 parents e42c4d7 + 283abbf commit 43c22af

File tree

121 files changed

+2831
-3021
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

121 files changed

+2831
-3021
lines changed

compiler/rustc_borrowck/src/constraint_generation.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ use crate::{
1414
places_conflict, region_infer::values::LivenessValues,
1515
};
1616

17-
pub(super) fn generate_constraints<'cx, 'tcx>(
18-
infcx: &InferCtxt<'cx, 'tcx>,
17+
pub(super) fn generate_constraints<'tcx>(
18+
infcx: &InferCtxt<'tcx>,
1919
liveness_constraints: &mut LivenessValues<RegionVid>,
2020
all_facts: &mut Option<AllFacts>,
2121
location_table: &LocationTable,
@@ -37,16 +37,16 @@ pub(super) fn generate_constraints<'cx, 'tcx>(
3737
}
3838

3939
/// 'cg = the duration of the constraint generation process itself.
40-
struct ConstraintGeneration<'cg, 'cx, 'tcx> {
41-
infcx: &'cg InferCtxt<'cx, 'tcx>,
40+
struct ConstraintGeneration<'cg, 'tcx> {
41+
infcx: &'cg InferCtxt<'tcx>,
4242
all_facts: &'cg mut Option<AllFacts>,
4343
location_table: &'cg LocationTable,
4444
liveness_constraints: &'cg mut LivenessValues<RegionVid>,
4545
borrow_set: &'cg BorrowSet<'tcx>,
4646
body: &'cg Body<'tcx>,
4747
}
4848

49-
impl<'cg, 'cx, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cg, 'cx, 'tcx> {
49+
impl<'cg, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cg, 'tcx> {
5050
fn visit_basic_block_data(&mut self, bb: BasicBlock, data: &BasicBlockData<'tcx>) {
5151
self.super_basic_block_data(bb, data);
5252
}
@@ -156,7 +156,7 @@ impl<'cg, 'cx, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cg, 'cx, 'tcx> {
156156
}
157157
}
158158

159-
impl<'cx, 'cg, 'tcx> ConstraintGeneration<'cx, 'cg, 'tcx> {
159+
impl<'cx, 'tcx> ConstraintGeneration<'cx, 'tcx> {
160160
/// Some variable with type `live_ty` is "regular live" at
161161
/// `location` -- i.e., it may be used later. This means that all
162162
/// regions appearing in the type `live_ty` must be live at

compiler/rustc_borrowck/src/consumers.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,8 @@ pub fn get_body_with_borrowck_facts<'tcx>(
3131
def: ty::WithOptConstParam<LocalDefId>,
3232
) -> BodyWithBorrowckFacts<'tcx> {
3333
let (input_body, promoted) = tcx.mir_promoted(def);
34-
tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bind(def.did)).enter(|infcx| {
35-
let input_body: &Body<'_> = &input_body.borrow();
36-
let promoted: &IndexVec<_, _> = &promoted.borrow();
37-
*super::do_mir_borrowck(&infcx, input_body, promoted, true).1.unwrap()
38-
})
34+
let infcx = tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bind(def.did)).build();
35+
let input_body: &Body<'_> = &input_body.borrow();
36+
let promoted: &IndexVec<_, _> = &promoted.borrow();
37+
*super::do_mir_borrowck(&infcx, input_body, promoted, true).1.unwrap()
3938
}

compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs

+58-94
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ impl<'tcx> UniverseInfo<'tcx> {
5656
) {
5757
match self.0 {
5858
UniverseInfoInner::RelateTys { expected, found } => {
59-
let err = mbcx.infcx.report_mismatched_types(
59+
let err = mbcx.infcx.err_ctxt().report_mismatched_types(
6060
&cause,
6161
expected,
6262
found,
@@ -238,20 +238,11 @@ impl<'tcx> TypeOpInfo<'tcx> for PredicateQuery<'tcx> {
238238
placeholder_region: ty::Region<'tcx>,
239239
error_region: Option<ty::Region<'tcx>>,
240240
) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
241-
mbcx.infcx.tcx.infer_ctxt().enter_with_canonical(
242-
cause.span,
243-
&self.canonical_query,
244-
|ref infcx, key, _| {
245-
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
246-
type_op_prove_predicate_with_cause(infcx, &mut *fulfill_cx, key, cause);
247-
try_extract_error_from_fulfill_cx(
248-
fulfill_cx,
249-
infcx,
250-
placeholder_region,
251-
error_region,
252-
)
253-
},
254-
)
241+
let (ref infcx, key, _) =
242+
mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
243+
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
244+
type_op_prove_predicate_with_cause(infcx, &mut *fulfill_cx, key, cause);
245+
try_extract_error_from_fulfill_cx(fulfill_cx, infcx, placeholder_region, error_region)
255246
}
256247
}
257248

@@ -288,37 +279,24 @@ where
288279
placeholder_region: ty::Region<'tcx>,
289280
error_region: Option<ty::Region<'tcx>>,
290281
) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
291-
mbcx.infcx.tcx.infer_ctxt().enter_with_canonical(
292-
cause.span,
293-
&self.canonical_query,
294-
|ref infcx, key, _| {
295-
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
296-
297-
let mut selcx = SelectionContext::new(infcx);
298-
299-
// FIXME(lqd): Unify and de-duplicate the following with the actual
300-
// `rustc_traits::type_op::type_op_normalize` query to allow the span we need in the
301-
// `ObligationCause`. The normalization results are currently different between
302-
// `AtExt::normalize` used in the query and `normalize` called below: the former fails
303-
// to normalize the `nll/relate_tys/impl-fn-ignore-binder-via-bottom.rs` test. Check
304-
// after #85499 lands to see if its fixes have erased this difference.
305-
let (param_env, value) = key.into_parts();
306-
let Normalized { value: _, obligations } = rustc_trait_selection::traits::normalize(
307-
&mut selcx,
308-
param_env,
309-
cause,
310-
value.value,
311-
);
312-
fulfill_cx.register_predicate_obligations(infcx, obligations);
313-
314-
try_extract_error_from_fulfill_cx(
315-
fulfill_cx,
316-
infcx,
317-
placeholder_region,
318-
error_region,
319-
)
320-
},
321-
)
282+
let (ref infcx, key, _) =
283+
mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
284+
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
285+
286+
let mut selcx = SelectionContext::new(infcx);
287+
288+
// FIXME(lqd): Unify and de-duplicate the following with the actual
289+
// `rustc_traits::type_op::type_op_normalize` query to allow the span we need in the
290+
// `ObligationCause`. The normalization results are currently different between
291+
// `AtExt::normalize` used in the query and `normalize` called below: the former fails
292+
// to normalize the `nll/relate_tys/impl-fn-ignore-binder-via-bottom.rs` test. Check
293+
// after #85499 lands to see if its fixes have erased this difference.
294+
let (param_env, value) = key.into_parts();
295+
let Normalized { value: _, obligations } =
296+
rustc_trait_selection::traits::normalize(&mut selcx, param_env, cause, value.value);
297+
fulfill_cx.register_predicate_obligations(infcx, obligations);
298+
299+
try_extract_error_from_fulfill_cx(fulfill_cx, infcx, placeholder_region, error_region)
322300
}
323301
}
324302

@@ -349,21 +327,11 @@ impl<'tcx> TypeOpInfo<'tcx> for AscribeUserTypeQuery<'tcx> {
349327
placeholder_region: ty::Region<'tcx>,
350328
error_region: Option<ty::Region<'tcx>>,
351329
) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
352-
mbcx.infcx.tcx.infer_ctxt().enter_with_canonical(
353-
cause.span,
354-
&self.canonical_query,
355-
|ref infcx, key, _| {
356-
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
357-
type_op_ascribe_user_type_with_span(infcx, &mut *fulfill_cx, key, Some(cause.span))
358-
.ok()?;
359-
try_extract_error_from_fulfill_cx(
360-
fulfill_cx,
361-
infcx,
362-
placeholder_region,
363-
error_region,
364-
)
365-
},
366-
)
330+
let (ref infcx, key, _) =
331+
mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
332+
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
333+
type_op_ascribe_user_type_with_span(infcx, &mut *fulfill_cx, key, Some(cause.span)).ok()?;
334+
try_extract_error_from_fulfill_cx(fulfill_cx, infcx, placeholder_region, error_region)
367335
}
368336
}
369337

@@ -407,7 +375,7 @@ impl<'tcx> TypeOpInfo<'tcx> for crate::type_check::InstantiateOpaqueType<'tcx> {
407375
#[instrument(skip(fulfill_cx, infcx), level = "debug")]
408376
fn try_extract_error_from_fulfill_cx<'tcx>(
409377
mut fulfill_cx: Box<dyn TraitEngine<'tcx> + 'tcx>,
410-
infcx: &InferCtxt<'_, 'tcx>,
378+
infcx: &InferCtxt<'tcx>,
411379
placeholder_region: ty::Region<'tcx>,
412380
error_region: Option<ty::Region<'tcx>>,
413381
) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
@@ -427,7 +395,7 @@ fn try_extract_error_from_fulfill_cx<'tcx>(
427395
}
428396

429397
fn try_extract_error_from_region_constraints<'tcx>(
430-
infcx: &InferCtxt<'_, 'tcx>,
398+
infcx: &InferCtxt<'tcx>,
431399
placeholder_region: ty::Region<'tcx>,
432400
error_region: Option<ty::Region<'tcx>>,
433401
region_constraints: &RegionConstraintData<'tcx>,
@@ -449,42 +417,38 @@ fn try_extract_error_from_region_constraints<'tcx>(
449417
})?;
450418

451419
debug!(?sub_region, "cause = {:#?}", cause);
452-
let nice_error = match (error_region, *sub_region) {
453-
(Some(error_region), ty::ReVar(vid)) => NiceRegionError::new(
454-
infcx,
455-
RegionResolutionError::SubSupConflict(
456-
vid,
457-
region_var_origin(vid),
458-
cause.clone(),
459-
error_region,
460-
cause.clone(),
461-
placeholder_region,
462-
vec![],
463-
),
464-
),
465-
(Some(error_region), _) => NiceRegionError::new(
466-
infcx,
467-
RegionResolutionError::ConcreteFailure(cause.clone(), error_region, placeholder_region),
420+
let error = match (error_region, *sub_region) {
421+
(Some(error_region), ty::ReVar(vid)) => RegionResolutionError::SubSupConflict(
422+
vid,
423+
region_var_origin(vid),
424+
cause.clone(),
425+
error_region,
426+
cause.clone(),
427+
placeholder_region,
428+
vec![],
468429
),
430+
(Some(error_region), _) => {
431+
RegionResolutionError::ConcreteFailure(cause.clone(), error_region, placeholder_region)
432+
}
469433
// Note universe here is wrong...
470-
(None, ty::ReVar(vid)) => NiceRegionError::new(
471-
infcx,
472-
RegionResolutionError::UpperBoundUniverseConflict(
473-
vid,
474-
region_var_origin(vid),
475-
universe_of_region(vid),
476-
cause.clone(),
477-
placeholder_region,
478-
),
479-
),
480-
(None, _) => NiceRegionError::new(
481-
infcx,
482-
RegionResolutionError::ConcreteFailure(cause.clone(), sub_region, placeholder_region),
434+
(None, ty::ReVar(vid)) => RegionResolutionError::UpperBoundUniverseConflict(
435+
vid,
436+
region_var_origin(vid),
437+
universe_of_region(vid),
438+
cause.clone(),
439+
placeholder_region,
483440
),
441+
(None, _) => {
442+
RegionResolutionError::ConcreteFailure(cause.clone(), sub_region, placeholder_region)
443+
}
484444
};
485-
nice_error.try_report_from_nll().or_else(|| {
445+
NiceRegionError::new(&infcx.err_ctxt(), error).try_report_from_nll().or_else(|| {
486446
if let SubregionOrigin::Subtype(trace) = cause {
487-
Some(infcx.report_and_explain_type_error(*trace, TypeError::RegionsPlaceholderMismatch))
447+
Some(
448+
infcx
449+
.err_ctxt()
450+
.report_and_explain_type_error(*trace, TypeError::RegionsPlaceholderMismatch),
451+
)
488452
} else {
489453
None
490454
}

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+36-38
Original file line numberDiff line numberDiff line change
@@ -492,11 +492,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
492492
let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
493493
return false;
494494
};
495-
tcx.infer_ctxt().enter(|infcx| {
496-
infcx
497-
.type_implements_trait(default_trait, ty, ty::List::empty(), param_env)
498-
.may_apply()
499-
})
495+
tcx.infer_ctxt()
496+
.build()
497+
.type_implements_trait(default_trait, ty, ty::List::empty(), param_env)
498+
.may_apply()
500499
};
501500

502501
let assign_value = match ty.kind() {
@@ -606,41 +605,40 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
606605
.and_then(|def_id| tcx.hir().get_generics(def_id))
607606
else { return; };
608607
// Try to find predicates on *generic params* that would allow copying `ty`
609-
let predicates: Result<Vec<_>, _> = tcx.infer_ctxt().enter(|infcx| {
610-
let mut fulfill_cx = <dyn rustc_infer::traits::TraitEngine<'_>>::new(infcx.tcx);
608+
let infcx = tcx.infer_ctxt().build();
609+
let mut fulfill_cx = <dyn rustc_infer::traits::TraitEngine<'_>>::new(infcx.tcx);
611610

612-
let copy_did = infcx.tcx.lang_items().copy_trait().unwrap();
613-
let cause = ObligationCause::new(
614-
span,
615-
self.mir_hir_id(),
616-
rustc_infer::traits::ObligationCauseCode::MiscObligation,
617-
);
618-
fulfill_cx.register_bound(
619-
&infcx,
620-
self.param_env,
621-
// Erase any region vids from the type, which may not be resolved
622-
infcx.tcx.erase_regions(ty),
623-
copy_did,
624-
cause,
625-
);
626-
// Select all, including ambiguous predicates
627-
let errors = fulfill_cx.select_all_or_error(&infcx);
628-
629-
// Only emit suggestion if all required predicates are on generic
630-
errors
631-
.into_iter()
632-
.map(|err| match err.obligation.predicate.kind().skip_binder() {
633-
PredicateKind::Trait(predicate) => match predicate.self_ty().kind() {
634-
ty::Param(param_ty) => Ok((
635-
generics.type_param(param_ty, tcx),
636-
predicate.trait_ref.print_only_trait_path().to_string(),
637-
)),
638-
_ => Err(()),
639-
},
611+
let copy_did = infcx.tcx.lang_items().copy_trait().unwrap();
612+
let cause = ObligationCause::new(
613+
span,
614+
self.mir_hir_id(),
615+
rustc_infer::traits::ObligationCauseCode::MiscObligation,
616+
);
617+
fulfill_cx.register_bound(
618+
&infcx,
619+
self.param_env,
620+
// Erase any region vids from the type, which may not be resolved
621+
infcx.tcx.erase_regions(ty),
622+
copy_did,
623+
cause,
624+
);
625+
// Select all, including ambiguous predicates
626+
let errors = fulfill_cx.select_all_or_error(&infcx);
627+
628+
// Only emit suggestion if all required predicates are on generic
629+
let predicates: Result<Vec<_>, _> = errors
630+
.into_iter()
631+
.map(|err| match err.obligation.predicate.kind().skip_binder() {
632+
PredicateKind::Trait(predicate) => match predicate.self_ty().kind() {
633+
ty::Param(param_ty) => Ok((
634+
generics.type_param(param_ty, tcx),
635+
predicate.trait_ref.print_only_trait_path().to_string(),
636+
)),
640637
_ => Err(()),
641-
})
642-
.collect()
643-
});
638+
},
639+
_ => Err(()),
640+
})
641+
.collect();
644642

645643
if let Ok(predicates) = predicates {
646644
suggest_constraining_type_params(

compiler/rustc_borrowck/src/diagnostics/mod.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1025,7 +1025,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
10251025
if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring {
10261026
let ty = moved_place.ty(self.body, self.infcx.tcx).ty;
10271027
let suggest = match self.infcx.tcx.get_diagnostic_item(sym::IntoIterator) {
1028-
Some(def_id) => self.infcx.tcx.infer_ctxt().enter(|infcx| {
1028+
Some(def_id) => {
1029+
let infcx = self.infcx.tcx.infer_ctxt().build();
10291030
type_known_to_meet_bound_modulo_regions(
10301031
&infcx,
10311032
self.param_env,
@@ -1036,7 +1037,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
10361037
def_id,
10371038
DUMMY_SP,
10381039
)
1039-
}),
1040+
}
10401041
_ => false,
10411042
};
10421043
if suggest {

compiler/rustc_borrowck/src/diagnostics/region_errors.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
186186
if let Some(lower_bound_region) = lower_bound_region {
187187
let generic_ty = type_test.generic_kind.to_ty(self.infcx.tcx);
188188
let origin = RelateParamBound(type_test_span, generic_ty, None);
189-
self.buffer_error(self.infcx.construct_generic_bound_failure(
189+
self.buffer_error(self.infcx.err_ctxt().construct_generic_bound_failure(
190190
self.body.source.def_id().expect_local(),
191191
type_test_span,
192192
Some(origin),
@@ -365,7 +365,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
365365

366366
// Check if we can use one of the "nice region errors".
367367
if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
368-
let nice = NiceRegionError::new_from_span(self.infcx, cause.span, o, f);
368+
let infer_err = self.infcx.err_ctxt();
369+
let nice = NiceRegionError::new_from_span(&infer_err, cause.span, o, f);
369370
if let Some(diag) = nice.try_report_from_nll() {
370371
self.buffer_error(diag);
371372
return;

0 commit comments

Comments
 (0)