1use std::collections::VecDeque;
2use std::fmt;
3use std::rc::Rc;
45use rustc_data_structures::frozen::Frozen;
6use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
7use rustc_data_structures::graph::scc::Sccs;
8use rustc_errors::Diag;
9use rustc_hir::def_id::CRATE_DEF_ID;
10use rustc_index::IndexVec;
11use rustc_infer::infer::outlives::test_type_match;
12use rustc_infer::infer::region_constraints::{GenericKind, VerifyBound, VerifyIfEq};
13use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin};
14use rustc_middle::bug;
15use rustc_middle::mir::{
16AnnotationSource, BasicBlock, Body, ConstraintCategory, Local, Location, ReturnConstraint,
17TerminatorKind,
18};
19use rustc_middle::traits::{ObligationCause, ObligationCauseCode};
20use rustc_middle::ty::{
21self, RegionExt, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex, fold_regions,
22};
23use rustc_mir_dataflow::points::DenseLocationMap;
24use rustc_span::hygiene::DesugaringKind;
25use rustc_span::{DUMMY_SP, Span};
26use tracing::{Level, debug, enabled, instrument, trace};
2728use crate::constraints::graph::NormalConstraintGraph;
29use crate::constraints::{ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet};
30use crate::dataflow::BorrowIndex;
31use crate::diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo};
32use crate::handle_placeholders::{LoweredConstraints, RegionTracker};
33use crate::polonius::LiveLoans;
34use crate::polonius::legacy::PoloniusOutput;
35use crate::region_infer::values::{LivenessValues, RegionElement, RegionValues};
36use crate::type_check::Locations;
37use crate::type_check::free_region_relations::UniversalRegionRelations;
38use crate::universal_regions::UniversalRegions;
39use crate::{
40BorrowckInferCtxt, ClosureOutlivesRequirement, ClosureOutlivesSubject,
41ClosureOutlivesSubjectTy, ClosureRegionRequirements,
42};
4344mod dump_mir;
45mod graphviz;
46pub(crate) mod opaque_types;
47mod reverse_sccs;
4849pub(crate) mod values;
5051/// The representative region variable for an SCC, tagged by its origin.
52/// We prefer placeholders over existentially quantified variables, otherwise
53/// it's the one with the smallest Region Variable ID. In other words,
54/// the order of this enumeration really matters!
55#[derive(#[automatically_derived]
impl ::core::marker::Copy for Representative { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Representative {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Representative::FreeRegion(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FreeRegion", &__self_0),
Representative::Placeholder(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Placeholder", &__self_0),
Representative::Existential(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Existential", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for Representative {
#[inline]
fn clone(&self) -> Representative {
let _: ::core::clone::AssertParamIsClone<RegionVid>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Representative {
#[inline]
fn eq(&self, other: &Representative) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(Representative::FreeRegion(__self_0),
Representative::FreeRegion(__arg1_0)) =>
__self_0 == __arg1_0,
(Representative::Placeholder(__self_0),
Representative::Placeholder(__arg1_0)) =>
__self_0 == __arg1_0,
(Representative::Existential(__self_0),
Representative::Existential(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Representative {
#[inline]
fn partial_cmp(&self, other: &Representative)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Eq for Representative {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<RegionVid>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::Ord for Representative {
#[inline]
fn cmp(&self, other: &Representative) -> ::core::cmp::Ordering {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
match ::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr) {
::core::cmp::Ordering::Equal =>
match (self, other) {
(Representative::FreeRegion(__self_0),
Representative::FreeRegion(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(Representative::Placeholder(__self_0),
Representative::Placeholder(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(Representative::Existential(__self_0),
Representative::Existential(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
_ => unsafe { ::core::intrinsics::unreachable() }
},
cmp => cmp,
}
}
}Ord)]
56pub(crate) enum Representative {
57 FreeRegion(RegionVid),
58 Placeholder(RegionVid),
59 Existential(RegionVid),
60}
6162impl Representative {
63pub(crate) fn rvid(self) -> RegionVid {
64match self {
65 Representative::FreeRegion(region_vid)
66 | Representative::Placeholder(region_vid)
67 | Representative::Existential(region_vid) => region_vid,
68 }
69 }
7071pub(crate) fn new(r: RegionVid, definition: &RegionDefinition<'_>) -> Self {
72match definition.origin {
73 NllRegionVariableOrigin::FreeRegion => Representative::FreeRegion(r),
74 NllRegionVariableOrigin::Placeholder(_) => Representative::Placeholder(r),
75 NllRegionVariableOrigin::Existential { .. } => Representative::Existential(r),
76 }
77 }
78}
7980pub(crate) type ConstraintSccs = Sccs<RegionVid, ConstraintSccIndex>;
8182pub struct RegionInferenceContext<'tcx> {
83/// Contains the definition for every region variable. Region
84 /// variables are identified by their index (`RegionVid`). The
85 /// definition contains information about where the region came
86 /// from as well as its final inferred value.
87pub(crate) definitions: Frozen<IndexVec<RegionVid, RegionDefinition<'tcx>>>,
8889/// The liveness constraints added to each region. For most
90 /// regions, these start out empty and steadily grow, though for
91 /// each universally quantified region R they start out containing
92 /// the entire CFG and `end(R)`.
93liveness_constraints: LivenessValues,
9495/// The outlives constraints computed by the type-check.
96constraints: Frozen<OutlivesConstraintSet<'tcx>>,
9798/// The constraint-set, but in graph form, making it easy to traverse
99 /// the constraints adjacent to a particular region. Used to construct
100 /// the SCC (see `constraint_sccs`) and for error reporting.
101constraint_graph: Frozen<NormalConstraintGraph>,
102103/// The SCC computed from `constraints` and the constraint
104 /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to
105 /// compute the values of each region.
106constraint_sccs: ConstraintSccs,
107108 scc_annotations: IndexVec<ConstraintSccIndex, RegionTracker>,
109110/// Map universe indexes to information on why we created it.
111universe_causes: FxIndexMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
112113/// The final inferred values of the region variables; we compute
114 /// one value per SCC. To get the value for any given *region*,
115 /// you first find which scc it is a part of.
116scc_values: RegionValues<'tcx, ConstraintSccIndex>,
117118/// Type constraints that we check after solving.
119type_tests: Vec<TypeTest<'tcx>>,
120121/// Information about how the universally quantified regions in
122 /// scope on this function relate to one another.
123universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
124}
125126#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for RegionDefinition<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"RegionDefinition", "origin", &self.origin, "universe",
&self.universe, "external_name", &&self.external_name)
}
}Debug)]
127pub(crate) struct RegionDefinition<'tcx> {
128/// What kind of variable is this -- a free region? existential
129 /// variable? etc. (See the `NllRegionVariableOrigin` for more
130 /// info.)
131pub(crate) origin: NllRegionVariableOrigin<'tcx>,
132133/// Which universe is this region variable defined in? This is
134 /// most often `ty::UniverseIndex::ROOT`, but when we encounter
135 /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
136 /// the variable for `'a` in a fresh universe that extends ROOT.
137pub(crate) universe: ty::UniverseIndex,
138139/// If this is 'static or an early-bound region, then this is
140 /// `Some(X)` where `X` is the name of the region.
141pub(crate) external_name: Option<ty::Region<'tcx>>,
142}
143144/// N.B., the variants in `Cause` are intentionally ordered. Lower
145/// values are preferred when it comes to error messages. Do not
146/// reorder willy nilly.
147#[derive(#[automatically_derived]
impl ::core::marker::Copy for Cause { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Cause {
#[inline]
fn clone(&self) -> Cause {
let _: ::core::clone::AssertParamIsClone<Local>;
let _: ::core::clone::AssertParamIsClone<Location>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Cause {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Cause::LiveVar(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"LiveVar", __self_0, &__self_1),
Cause::DropVar(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"DropVar", __self_0, &__self_1),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialOrd for Cause {
#[inline]
fn partial_cmp(&self, other: &Cause)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for Cause {
#[inline]
fn cmp(&self, other: &Cause) -> ::core::cmp::Ordering {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
match ::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr) {
::core::cmp::Ordering::Equal =>
match (self, other) {
(Cause::LiveVar(__self_0, __self_1),
Cause::LiveVar(__arg1_0, __arg1_1)) =>
match ::core::cmp::Ord::cmp(__self_0, __arg1_0) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(__self_1, __arg1_1),
cmp => cmp,
},
(Cause::DropVar(__self_0, __self_1),
Cause::DropVar(__arg1_0, __arg1_1)) =>
match ::core::cmp::Ord::cmp(__self_0, __arg1_0) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(__self_1, __arg1_1),
cmp => cmp,
},
_ => unsafe { ::core::intrinsics::unreachable() }
},
cmp => cmp,
}
}
}Ord, #[automatically_derived]
impl ::core::cmp::PartialEq for Cause {
#[inline]
fn eq(&self, other: &Cause) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(Cause::LiveVar(__self_0, __self_1),
Cause::LiveVar(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(Cause::DropVar(__self_0, __self_1),
Cause::DropVar(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Cause {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Local>;
let _: ::core::cmp::AssertParamIsEq<Location>;
}
}Eq)]
148pub(crate) enum Cause {
149/// point inserted because Local was live at the given Location
150LiveVar(Local, Location),
151152/// point inserted because Local was dropped at the given Location
153DropVar(Local, Location),
154}
155156/// A "type test" corresponds to an outlives constraint between a type
157/// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
158/// translated from the `Verify` region constraints in the ordinary
159/// inference context.
160///
161/// These sorts of constraints are handled differently than ordinary
162/// constraints, at least at present. During type checking, the
163/// `InferCtxt::process_registered_region_obligations` method will
164/// attempt to convert a type test like `T: 'x` into an ordinary
165/// outlives constraint when possible (for example, `&'a T: 'b` will
166/// be converted into `'a: 'b` and registered as a `Constraint`).
167///
168/// In some cases, however, there are outlives relationships that are
169/// not converted into a region constraint, but rather into one of
170/// these "type tests". The distinction is that a type test does not
171/// influence the inference result, but instead just examines the
172/// values that we ultimately inferred for each region variable and
173/// checks that they meet certain extra criteria. If not, an error
174/// can be issued.
175///
176/// One reason for this is that these type tests typically boil down
177/// to a check like `'a: 'x` where `'a` is a universally quantified
178/// region -- and therefore not one whose value is really meant to be
179/// *inferred*, precisely (this is not always the case: one can have a
180/// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
181/// inference variable). Another reason is that these type tests can
182/// involve *disjunction* -- that is, they can be satisfied in more
183/// than one way.
184///
185/// For more information about this translation, see
186/// `InferCtxt::process_registered_region_obligations` and
187/// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`.
188#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeTest<'tcx> {
#[inline]
fn clone(&self) -> TypeTest<'tcx> {
TypeTest {
generic_kind: ::core::clone::Clone::clone(&self.generic_kind),
lower_bound: ::core::clone::Clone::clone(&self.lower_bound),
span: ::core::clone::Clone::clone(&self.span),
verify_bound: ::core::clone::Clone::clone(&self.verify_bound),
}
}
}Clone)]
189pub(crate) struct TypeTest<'tcx> {
190/// The type `T` that must outlive the region.
191pub generic_kind: GenericKind<'tcx>,
192193/// The region `'x` that the type must outlive.
194pub lower_bound: RegionVid,
195196/// The span to blame.
197pub span: Span,
198199/// A test which, if met by the region `'x`, proves that this type
200 /// constraint is satisfied.
201pub verify_bound: VerifyBound<'tcx>,
202}
203204impl fmt::Debugfor TypeTest<'_> {
205fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206fn fmt_bound(
207 f: &mut fmt::Formatter<'_>,
208 generic_kind: GenericKind<'_>,
209 lower: RegionVid,
210 bound: &VerifyBound<'_>,
211 ) -> fmt::Result {
212let fmt_bounds =
213 |f: &mut fmt::Formatter<'_>, bounds: &[VerifyBound<'_>]| -> fmt::Result {
214let mut it = bounds.iter().peekable();
215while let Some(bound) = it.next() {
216 fmt_bound(f, generic_kind, lower, bound)?;
217if it.peek().is_some() {
218f.write_fmt(format_args!(", "))write!(f, ", ")?
219}
220 }
221Ok(())
222 };
223match bound {
224 VerifyBound::IfEq(binder) => f.write_fmt(format_args!("{0:?} == {1:?}", generic_kind, binder))write!(f, "{:?} == {:?}", generic_kind, binder),
225 VerifyBound::OutlivedBy(region) => f.write_fmt(format_args!("{0:?}: {1:?}", region, lower))write!(f, "{region:?}: {lower:?}"),
226 VerifyBound::AnyBound(verify_bounds) => {
227f.write_fmt(format_args!("Any["))write!(f, "Any[")?;
228 fmt_bounds(f, verify_bounds)?;
229f.write_fmt(format_args!("]"))write!(f, "]")230 }
231 VerifyBound::AllBounds(verify_bounds) => {
232f.write_fmt(format_args!("All["))write!(f, "All[")?;
233 fmt_bounds(f, verify_bounds)?;
234f.write_fmt(format_args!("]"))write!(f, "]")235 }
236 VerifyBound::IsEmpty => f.write_fmt(format_args!("Empty({0:?})", lower))write!(f, "Empty({lower:?})"),
237 }
238 }
239f.write_fmt(format_args!("TypeTest from {0:?}[", self.span))write!(f, "TypeTest from {:?}[", self.span)?;
240 fmt_bound(f, self.generic_kind, self.lower_bound, &self.verify_bound)?;
241f.write_fmt(format_args!("] ⊢ {0:?}: {1:?}", self.generic_kind,
self.lower_bound))write!(f, "] ⊢ {:?}: {:?}", self.generic_kind, self.lower_bound)242 }
243}
244245/// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure
246/// environment). If we can't, it is an error.
247#[derive(#[automatically_derived]
impl ::core::clone::Clone for RegionRelationCheckResult {
#[inline]
fn clone(&self) -> RegionRelationCheckResult { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for RegionRelationCheckResult { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for RegionRelationCheckResult {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
RegionRelationCheckResult::Ok => "Ok",
RegionRelationCheckResult::Propagated => "Propagated",
RegionRelationCheckResult::Error => "Error",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for RegionRelationCheckResult {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for RegionRelationCheckResult {
#[inline]
fn eq(&self, other: &RegionRelationCheckResult) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
248enum RegionRelationCheckResult {
249Ok,
250 Propagated,
251 Error,
252}
253254#[derive(#[automatically_derived]
impl<'a, 'tcx> ::core::clone::Clone for Trace<'a, 'tcx> {
#[inline]
fn clone(&self) -> Trace<'a, 'tcx> {
match self {
Trace::StartRegion => Trace::StartRegion,
Trace::FromGraph(__self_0) =>
Trace::FromGraph(::core::clone::Clone::clone(__self_0)),
Trace::FromStatic(__self_0) =>
Trace::FromStatic(::core::clone::Clone::clone(__self_0)),
Trace::NotVisited => Trace::NotVisited,
}
}
}Clone, #[automatically_derived]
impl<'a, 'tcx> ::core::cmp::PartialEq for Trace<'a, 'tcx> {
#[inline]
fn eq(&self, other: &Trace<'a, 'tcx>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(Trace::FromGraph(__self_0), Trace::FromGraph(__arg1_0)) =>
__self_0 == __arg1_0,
(Trace::FromStatic(__self_0), Trace::FromStatic(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'a, 'tcx> ::core::cmp::Eq for Trace<'a, 'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<&'a OutlivesConstraint<'tcx>>;
let _: ::core::cmp::AssertParamIsEq<RegionVid>;
}
}Eq, #[automatically_derived]
impl<'a, 'tcx> ::core::fmt::Debug for Trace<'a, 'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Trace::StartRegion =>
::core::fmt::Formatter::write_str(f, "StartRegion"),
Trace::FromGraph(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FromGraph", &__self_0),
Trace::FromStatic(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FromStatic", &__self_0),
Trace::NotVisited =>
::core::fmt::Formatter::write_str(f, "NotVisited"),
}
}
}Debug)]
255enum Trace<'a, 'tcx> {
256 StartRegion,
257 FromGraph(&'a OutlivesConstraint<'tcx>),
258 FromStatic(RegionVid),
259 NotVisited,
260}
261262#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("sccs_info",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(262u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
use crate::renumber::RegionCtxt;
let var_to_origin = infcx.reg_var_to_origin.borrow();
let mut var_to_origin_sorted =
var_to_origin.clone().into_iter().collect::<Vec<_>>();
var_to_origin_sorted.sort_by_key(|vto| vto.0);
if {
if Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("enabled compiler/rustc_borrowck/src/region_infer/mod.rs:271",
"rustc_borrowck::region_infer", Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(271u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::HINT.hint())
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let interest = __CALLSITE.interest();
if !interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::dispatcher::get_default(|current|
current.enabled(meta))
} else { false }
} else { false }
} {
let mut reg_vars_to_origins_str =
"region variables to origins:\n".to_string();
for (reg_var, origin) in var_to_origin_sorted.into_iter() {
reg_vars_to_origins_str.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}: {1:?}\n", reg_var,
origin))
}));
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:276",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(276u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0}",
reg_vars_to_origins_str) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
}
let num_components = sccs.num_sccs();
let mut components =
::alloc::vec::from_elem(FxIndexSet::default(),
num_components);
for (reg_var, scc_idx) in sccs.scc_indices().iter_enumerated() {
let origin =
var_to_origin.get(®_var).unwrap_or(&RegionCtxt::Unknown);
components[scc_idx.as_usize()].insert((reg_var, *origin));
}
if {
if Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("enabled compiler/rustc_borrowck/src/region_infer/mod.rs:287",
"rustc_borrowck::region_infer", Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(287u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::HINT.hint())
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let interest = __CALLSITE.interest();
if !interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::dispatcher::get_default(|current|
current.enabled(meta))
} else { false }
} else { false }
} {
let mut components_str =
"strongly connected components:".to_string();
for (scc_idx, reg_vars_origins) in
components.iter().enumerate() {
let regions_info =
reg_vars_origins.clone().into_iter().collect::<Vec<_>>();
components_str.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}: {1:?},\n)",
ConstraintSccIndex::from_usize(scc_idx), regions_info))
}))
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:297",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(297u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0}",
components_str) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
}
let components_representatives =
components.into_iter().enumerate().map(|(scc_idx,
region_ctxts)|
{
let repr =
region_ctxts.into_iter().map(|reg_var_origin|
reg_var_origin.1).max_by(|x, y|
x.preference_value().cmp(&y.preference_value())).unwrap();
(ConstraintSccIndex::from_usize(scc_idx), repr)
}).collect::<FxIndexMap<_, _>>();
let mut scc_node_to_edges = FxIndexMap::default();
for (scc_idx, repr) in components_representatives.iter() {
let edge_representatives =
sccs.successors(*scc_idx).iter().map(|scc_idx|
components_representatives[scc_idx]).collect::<Vec<_>>();
scc_node_to_edges.insert((scc_idx, repr),
edge_representatives);
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:325",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(325u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("SCC edges {0:#?}",
scc_node_to_edges) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
}
}
}#[instrument(skip(infcx, sccs), level = "debug")]263fn sccs_info<'tcx>(infcx: &BorrowckInferCtxt<'tcx>, sccs: &ConstraintSccs) {
264use crate::renumber::RegionCtxt;
265266let var_to_origin = infcx.reg_var_to_origin.borrow();
267268let mut var_to_origin_sorted = var_to_origin.clone().into_iter().collect::<Vec<_>>();
269 var_to_origin_sorted.sort_by_key(|vto| vto.0);
270271if enabled!(Level::DEBUG) {
272let mut reg_vars_to_origins_str = "region variables to origins:\n".to_string();
273for (reg_var, origin) in var_to_origin_sorted.into_iter() {
274 reg_vars_to_origins_str.push_str(&format!("{reg_var:?}: {origin:?}\n"));
275 }
276debug!("{}", reg_vars_to_origins_str);
277 }
278279let num_components = sccs.num_sccs();
280let mut components = vec![FxIndexSet::default(); num_components];
281282for (reg_var, scc_idx) in sccs.scc_indices().iter_enumerated() {
283let origin = var_to_origin.get(®_var).unwrap_or(&RegionCtxt::Unknown);
284 components[scc_idx.as_usize()].insert((reg_var, *origin));
285 }
286287if enabled!(Level::DEBUG) {
288let mut components_str = "strongly connected components:".to_string();
289for (scc_idx, reg_vars_origins) in components.iter().enumerate() {
290let regions_info = reg_vars_origins.clone().into_iter().collect::<Vec<_>>();
291 components_str.push_str(&format!(
292"{:?}: {:?},\n)",
293 ConstraintSccIndex::from_usize(scc_idx),
294 regions_info,
295 ))
296 }
297debug!("{}", components_str);
298 }
299300// calculate the best representative for each component
301let components_representatives = components
302 .into_iter()
303 .enumerate()
304 .map(|(scc_idx, region_ctxts)| {
305let repr = region_ctxts
306 .into_iter()
307 .map(|reg_var_origin| reg_var_origin.1)
308 .max_by(|x, y| x.preference_value().cmp(&y.preference_value()))
309 .unwrap();
310311 (ConstraintSccIndex::from_usize(scc_idx), repr)
312 })
313 .collect::<FxIndexMap<_, _>>();
314315let mut scc_node_to_edges = FxIndexMap::default();
316for (scc_idx, repr) in components_representatives.iter() {
317let edge_representatives = sccs
318 .successors(*scc_idx)
319 .iter()
320 .map(|scc_idx| components_representatives[scc_idx])
321 .collect::<Vec<_>>();
322 scc_node_to_edges.insert((scc_idx, repr), edge_representatives);
323 }
324325debug!("SCC edges {:#?}", scc_node_to_edges);
326}
327328impl<'tcx> RegionInferenceContext<'tcx> {
329/// Creates a new region inference context with a total of
330 /// `num_region_variables` valid inference variables; the first N
331 /// of those will be constant regions representing the free
332 /// regions defined in `universal_regions`.
333 ///
334 /// The `outlives_constraints` and `type_tests` are an initial set
335 /// of constraints produced by the MIR type check.
336pub(crate) fn new(
337 infcx: &BorrowckInferCtxt<'tcx>,
338 lowered_constraints: LoweredConstraints<'tcx>,
339 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
340 location_map: Rc<DenseLocationMap>,
341 ) -> Self {
342let universal_regions = &universal_region_relations.universal_regions;
343344let LoweredConstraints {
345 constraint_sccs,
346 definitions,
347 outlives_constraints,
348 scc_annotations,
349 type_tests,
350mut liveness_constraints,
351 universe_causes,
352 placeholder_indices,
353 } = lowered_constraints;
354355{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:355",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(355u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("universal_regions: {0:#?}",
universal_region_relations.universal_regions) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("universal_regions: {:#?}", universal_region_relations.universal_regions);
356{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:356",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(356u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("outlives constraints: {0:#?}",
outlives_constraints) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("outlives constraints: {:#?}", outlives_constraints);
357{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:357",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(357u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("placeholder_indices: {0:#?}",
placeholder_indices) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("placeholder_indices: {:#?}", placeholder_indices);
358{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:358",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(358u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("type tests: {0:#?}",
type_tests) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("type tests: {:#?}", type_tests);
359360let constraint_graph = Frozen::freeze(outlives_constraints.graph(definitions.len()));
361362if truecfg!(debug_assertions) {
363sccs_info(infcx, &constraint_sccs);
364 }
365366let mut scc_values =
367RegionValues::new(location_map, universal_regions.len(), placeholder_indices);
368369// Initializes the region variables with their initial live points.
370for (region, definition) in definitions.iter_enumerated() {
371let scc = constraint_sccs.scc(region);
372373// For each universally quantified region (lifetime parameter). The
374 // first N variables always correspond to the regions appearing in the
375 // function signature (both named and anonymous) and in where-clauses.
376match definition.origin {
377// For each free, universally quantified region X:
378NllRegionVariableOrigin::FreeRegion => {
379// Add all nodes in the CFG to liveness constraints
380liveness_constraints.add_all_points(region);
381382// Add `end(X)` into the set for X.
383scc_values.add_free_region(scc, region);
384 }
385386 NllRegionVariableOrigin::Placeholder(placeholder) => {
387 scc_values.add_placeholder(scc, placeholder);
388 }
389390 NllRegionVariableOrigin::Existential { .. } => {
391// For existential, regions, nothing to do.
392}
393 }
394395// Initially copy the liveness constraints of any region that
396 // has them, setting `scc_values[scc(region)] |= liveness_constraints[region]`.
397 //
398 // These values will later be propagated during [`Self::propagate_constraints()`].
399 // The values include any live-at-all-points constraints added above
400 // for free regions.
401if let Some(liveness) = liveness_constraints.point_liveness(region) {
402 scc_values.merge_liveness(scc, liveness)
403 }
404 }
405406Self {
407definitions,
408liveness_constraints,
409 constraints: outlives_constraints,
410constraint_graph,
411constraint_sccs,
412scc_annotations,
413universe_causes,
414scc_values,
415type_tests,
416universal_region_relations,
417 }
418 }
419420/// Returns an iterator over all the region indices.
421pub(crate) fn regions(&self) -> impl Iterator<Item = RegionVid> + 'tcx {
422self.definitions.indices()
423 }
424425/// Given a universal region in scope on the MIR, returns the
426 /// corresponding index.
427 ///
428 /// Panics if `r` is not a registered universal region, most notably
429 /// if it is a placeholder. Handling placeholders requires access to the
430 /// `MirTypeckRegionConstraints`.
431pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
432self.universal_regions().to_region_vid(r)
433 }
434435/// Returns an iterator over all the outlives constraints.
436pub(crate) fn outlives_constraints(&self) -> impl Iterator<Item = OutlivesConstraint<'tcx>> {
437self.constraints.outlives().iter().copied()
438 }
439440/// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
441pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {
442self.universal_regions().annotate(tcx, err)
443 }
444445/// Returns `true` if the region `r` contains the point `p`.
446 ///
447 /// Panics if called before `solve()` executes,
448pub(crate) fn region_contains_point(&self, r: RegionVid, p: Location) -> bool {
449let scc = self.constraint_sccs.scc(r);
450self.scc_values.contains_point(scc, p)
451 }
452453/// Returns the lowest statement index in `start..=end` which is not contained by `r`.
454 ///
455 /// Panics if called before `solve()` executes.
456pub(crate) fn first_non_contained_inclusive(
457&self,
458 r: RegionVid,
459 block: BasicBlock,
460 start: usize,
461 end: usize,
462 ) -> Option<usize> {
463let scc = self.constraint_sccs.scc(r);
464self.scc_values.first_non_contained_inclusive(scc, block, start, end)
465 }
466467/// Returns access to the value of `r` for debugging purposes.
468pub(crate) fn region_value_str(&self, r: RegionVid) -> String {
469let scc = self.constraint_sccs.scc(r);
470self.scc_values.region_value_str(scc)
471 }
472473pub(crate) fn placeholders_contained_in(
474&self,
475 r: RegionVid,
476 ) -> impl Iterator<Item = ty::PlaceholderRegion<'tcx>> {
477let scc = self.constraint_sccs.scc(r);
478self.scc_values.placeholders_contained_in(scc)
479 }
480481/// Performs region inference and report errors if we see any
482 /// unsatisfiable constraints. If this is a closure, returns the
483 /// region requirements to propagate to our creator, if any.
484#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("solve",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(484u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
(Option<ClosureRegionRequirements<'tcx>>,
RegionErrors<'tcx>) = loop {};
return __tracing_attr_fake_return;
}
{
let mir_def_id = body.source.def_id();
self.propagate_constraints();
let mut errors_buffer = RegionErrors::new(infcx.tcx);
let mut propagated_outlives_requirements =
infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);
self.check_type_tests(infcx,
propagated_outlives_requirements.as_mut(),
&mut errors_buffer);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:504",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(504u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("errors_buffer")
}> =
::tracing::__macro_support::FieldName::new("errors_buffer");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&errors_buffer)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:505",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(505u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("propagated_outlives_requirements")
}> =
::tracing::__macro_support::FieldName::new("propagated_outlives_requirements");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&propagated_outlives_requirements)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
if infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled()
{
self.check_polonius_subset_errors(propagated_outlives_requirements.as_mut(),
&mut errors_buffer,
polonius_output.as_ref().expect("Polonius output is unavailable despite `-Z polonius`"));
} else {
self.check_universal_regions(propagated_outlives_requirements.as_mut(),
&mut errors_buffer);
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:525",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(525u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("errors_buffer")
}> =
::tracing::__macro_support::FieldName::new("errors_buffer");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&errors_buffer)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let propagated_outlives_requirements =
propagated_outlives_requirements.unwrap_or_default();
if propagated_outlives_requirements.is_empty() {
(None, errors_buffer)
} else {
let num_external_vids =
self.universal_regions().num_global_and_external_regions();
(Some(ClosureRegionRequirements {
num_external_vids,
outlives_requirements: propagated_outlives_requirements,
}), errors_buffer)
}
}
}
}#[instrument(skip(self, infcx, body, polonius_output), level = "debug")]485pub(super) fn solve(
486&mut self,
487 infcx: &InferCtxt<'tcx>,
488 body: &Body<'tcx>,
489 polonius_output: Option<Box<PoloniusOutput>>,
490 ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) {
491let mir_def_id = body.source.def_id();
492self.propagate_constraints();
493494let mut errors_buffer = RegionErrors::new(infcx.tcx);
495496// If this is a nested body, we propagate unsatisfied
497 // outlives constraints to the parent body instead of
498 // eagerly erroing.
499let mut propagated_outlives_requirements =
500 infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);
501502self.check_type_tests(infcx, propagated_outlives_requirements.as_mut(), &mut errors_buffer);
503504debug!(?errors_buffer);
505debug!(?propagated_outlives_requirements);
506507// In Polonius mode, the errors about missing universal region relations are in the output
508 // and need to be emitted or propagated. Otherwise, we need to check whether the
509 // constraints were too strong, and if so, emit or propagate those errors.
510if infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled() {
511self.check_polonius_subset_errors(
512 propagated_outlives_requirements.as_mut(),
513&mut errors_buffer,
514 polonius_output
515 .as_ref()
516 .expect("Polonius output is unavailable despite `-Z polonius`"),
517 );
518 } else {
519self.check_universal_regions(
520 propagated_outlives_requirements.as_mut(),
521&mut errors_buffer,
522 );
523 }
524525debug!(?errors_buffer);
526527let propagated_outlives_requirements = propagated_outlives_requirements.unwrap_or_default();
528529if propagated_outlives_requirements.is_empty() {
530 (None, errors_buffer)
531 } else {
532let num_external_vids = self.universal_regions().num_global_and_external_regions();
533 (
534Some(ClosureRegionRequirements {
535 num_external_vids,
536 outlives_requirements: propagated_outlives_requirements,
537 }),
538 errors_buffer,
539 )
540 }
541 }
542543/// Propagate the region constraints: this will grow the values
544 /// for each region variable until all the constraints are
545 /// satisfied. Note that some values may grow **too** large to be
546 /// feasible, but we check this later.
547#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("propagate_constraints",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(547u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:549",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(549u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("constraints={0:#?}",
{
let mut constraints: Vec<_> =
self.outlives_constraints().collect();
constraints.sort_by_key(|c| (c.sup, c.sub));
constraints.into_iter().map(|c|
(c, self.constraint_sccs.scc(c.sup),
self.constraint_sccs.scc(c.sub))).collect::<Vec<_>>()
}) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
for scc_a in self.constraint_sccs.all_sccs() {
for &scc_b in self.constraint_sccs.successors(scc_a) {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:566",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(566u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("scc_b")
}> =
::tracing::__macro_support::FieldName::new("scc_b");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scc_b)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
self.scc_values.add_region(scc_a, scc_b);
}
}
}
}
}#[instrument(skip(self), level = "debug")]548fn propagate_constraints(&mut self) {
549debug!("constraints={:#?}", {
550let mut constraints: Vec<_> = self.outlives_constraints().collect();
551 constraints.sort_by_key(|c| (c.sup, c.sub));
552 constraints
553 .into_iter()
554 .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))
555 .collect::<Vec<_>>()
556 });
557558// To propagate constraints, we walk the DAG induced by the
559 // SCC. For each SCC `A`, we visit its successors and compute
560 // their values, then we union all those values to get our
561 // own. This one-shot approach works because iteration is in
562 // dependency order. I.e. a chain A: B: C will visit C, B, A.
563for scc_a in self.constraint_sccs.all_sccs() {
564// Walk each SCC `B` such that `A: B`...
565for &scc_b in self.constraint_sccs.successors(scc_a) {
566debug!(?scc_b);
567self.scc_values.add_region(scc_a, scc_b);
568 }
569 }
570 }
571572/// Returns `true` if all the placeholders in the value of `scc_b` are nameable
573 /// in `scc_a`. Used during constraint propagation, and only once
574 /// the value of `scc_b` has been computed.
575fn can_name_all_placeholders(
576&self,
577 scc_a: ConstraintSccIndex,
578 scc_b: ConstraintSccIndex,
579 ) -> bool {
580self.scc_annotations[scc_a].can_name_all_placeholders(self.scc_annotations[scc_b])
581 }
582583/// Once regions have been propagated, this method is used to see
584 /// whether the "type tests" produced by typeck were satisfied;
585 /// type tests encode type-outlives relationships like `T:
586 /// 'a`. See `TypeTest` for more details.
587fn check_type_tests(
588&self,
589 infcx: &InferCtxt<'tcx>,
590mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
591 errors_buffer: &mut RegionErrors<'tcx>,
592 ) {
593let tcx = infcx.tcx;
594595// Sometimes we register equivalent type-tests that would
596 // result in basically the exact same error being reported to
597 // the user. Avoid that.
598let mut deduplicate_errors = FxIndexSet::default();
599600for type_test in &self.type_tests {
601{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:601",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(601u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_type_test: {0:?}",
type_test) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_type_test: {:?}", type_test);
602603let generic_ty = type_test.generic_kind.to_ty(tcx);
604if self.eval_verify_bound(
605 infcx,
606 generic_ty,
607 type_test.lower_bound,
608&type_test.verify_bound,
609 ) {
610continue;
611 }
612613if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements
614 && self.try_promote_type_test(infcx, type_test, propagated_outlives_requirements)
615 {
616continue;
617 }
618619// Type-test failed. Report the error.
620let erased_generic_kind = infcx.tcx.erase_and_anonymize_regions(type_test.generic_kind);
621622// Skip duplicate-ish errors.
623if deduplicate_errors.insert((
624 erased_generic_kind,
625 type_test.lower_bound,
626 type_test.span,
627 )) {
628{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:628",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(628u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_type_test: reporting error for erased_generic_kind={0:?}, lower_bound_region={1:?}, type_test.span={2:?}",
erased_generic_kind, type_test.lower_bound, type_test.span)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
629"check_type_test: reporting error for erased_generic_kind={:?}, \
630 lower_bound_region={:?}, \
631 type_test.span={:?}",
632 erased_generic_kind, type_test.lower_bound, type_test.span,
633 );
634635 errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() });
636 }
637 }
638 }
639640/// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
641 /// prove to be satisfied. If this is a closure, we will attempt to
642 /// "promote" this type-test into our `ClosureRegionRequirements` and
643 /// hence pass it up the creator. To do this, we have to phrase the
644 /// type-test in terms of external free regions, as local free
645 /// regions are not nameable by the closure's creator.
646 ///
647 /// Promotion works as follows: we first check that the type `T`
648 /// contains only regions that the creator knows about. If this is
649 /// true, then -- as a consequence -- we know that all regions in
650 /// the type `T` are free regions that outlive the closure body. If
651 /// false, then promotion fails.
652 ///
653 /// Once we've promoted T, we have to "promote" `'X` to some region
654 /// that is "external" to the closure. Generally speaking, a region
655 /// may be the union of some points in the closure body as well as
656 /// various free lifetimes. We can ignore the points in the closure
657 /// body: if the type T can be expressed in terms of external regions,
658 /// we know it outlives the points in the closure body. That
659 /// just leaves the free regions.
660 ///
661 /// The idea then is to lower the `T: 'X` constraint into multiple
662 /// bounds -- e.g., if `'X` is the union of two free lifetimes,
663 /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
664#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("try_promote_type_test",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(664u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("type_test")
}> =
::tracing::__macro_support::FieldName::new("type_test");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&type_test)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = infcx.tcx;
let TypeTest {
generic_kind, lower_bound, span: blame_span, verify_bound: _
} = *type_test;
let generic_ty = generic_kind.to_ty(tcx);
let Some(subject) =
self.try_promote_type_test_subject(infcx,
generic_ty) else { return false; };
let r_scc = self.constraint_sccs.scc(lower_bound);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:680",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(680u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("lower_bound = {0:?} r_scc={1:?} universe={2:?}",
lower_bound, r_scc, self.max_nameable_universe(r_scc)) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
if let Some(p) =
self.scc_values.placeholders_contained_in(r_scc).next() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:693",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(693u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("encountered placeholder in higher universe: {0:?}, requiring \'static",
p) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let static_r = self.universal_regions().fr_static;
propagated_outlives_requirements.push(ClosureOutlivesRequirement {
subject,
outlived_free_region: static_r,
blame_span,
category: ConstraintCategory::Boring,
});
return true;
}
let mut found_outlived_universal_region = false;
for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
found_outlived_universal_region = true;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:713",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(713u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("universal_region_outlived_by ur={0:?}",
ur) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let non_local_ub =
self.universal_region_relations.non_local_upper_bounds(ur);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:715",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(715u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("non_local_ub")
}> =
::tracing::__macro_support::FieldName::new("non_local_ub");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&non_local_ub)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
for upper_bound in non_local_ub {
if true {
if !self.universal_regions().is_universal_region(upper_bound)
{
::core::panicking::panic("assertion failed: self.universal_regions().is_universal_region(upper_bound)")
};
};
if true {
if !!self.universal_regions().is_local_free_region(upper_bound)
{
::core::panicking::panic("assertion failed: !self.universal_regions().is_local_free_region(upper_bound)")
};
};
let requirement =
ClosureOutlivesRequirement {
subject,
outlived_free_region: upper_bound,
blame_span,
category: ConstraintCategory::Boring,
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:731",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(731u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("requirement")
}> =
::tracing::__macro_support::FieldName::new("requirement");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("adding closure requirement")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&requirement)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
propagated_outlives_requirements.push(requirement);
}
}
if !found_outlived_universal_region {
::core::panicking::panic("assertion failed: found_outlived_universal_region")
};
true
}
}
}#[instrument(level = "debug", skip(self, infcx, propagated_outlives_requirements))]665fn try_promote_type_test(
666&self,
667 infcx: &InferCtxt<'tcx>,
668 type_test: &TypeTest<'tcx>,
669 propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,
670 ) -> bool {
671let tcx = infcx.tcx;
672let TypeTest { generic_kind, lower_bound, span: blame_span, verify_bound: _ } = *type_test;
673674let generic_ty = generic_kind.to_ty(tcx);
675let Some(subject) = self.try_promote_type_test_subject(infcx, generic_ty) else {
676return false;
677 };
678679let r_scc = self.constraint_sccs.scc(lower_bound);
680debug!(
681"lower_bound = {:?} r_scc={:?} universe={:?}",
682 lower_bound,
683 r_scc,
684self.max_nameable_universe(r_scc)
685 );
686// If the type test requires that `T: 'a` where `'a` is a
687 // placeholder from another universe, that effectively requires
688 // `T: 'static`, so we have to propagate that requirement.
689 //
690 // It doesn't matter *what* universe because the promoted `T` will
691 // always be in the root universe.
692if let Some(p) = self.scc_values.placeholders_contained_in(r_scc).next() {
693debug!("encountered placeholder in higher universe: {:?}, requiring 'static", p);
694let static_r = self.universal_regions().fr_static;
695 propagated_outlives_requirements.push(ClosureOutlivesRequirement {
696 subject,
697 outlived_free_region: static_r,
698 blame_span,
699 category: ConstraintCategory::Boring,
700 });
701702// we can return here -- the code below might push add'l constraints
703 // but they would all be weaker than this one.
704return true;
705 }
706707// For each region outlived by lower_bound find a non-local,
708 // universal region (it may be the same region) and add it to
709 // `ClosureOutlivesRequirement`.
710let mut found_outlived_universal_region = false;
711for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
712 found_outlived_universal_region = true;
713debug!("universal_region_outlived_by ur={:?}", ur);
714let non_local_ub = self.universal_region_relations.non_local_upper_bounds(ur);
715debug!(?non_local_ub);
716717// This is slightly too conservative. To show T: '1, given `'2: '1`
718 // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
719 // avoid potential non-determinism we approximate this by requiring
720 // T: '1 and T: '2.
721for upper_bound in non_local_ub {
722debug_assert!(self.universal_regions().is_universal_region(upper_bound));
723debug_assert!(!self.universal_regions().is_local_free_region(upper_bound));
724725let requirement = ClosureOutlivesRequirement {
726 subject,
727 outlived_free_region: upper_bound,
728 blame_span,
729 category: ConstraintCategory::Boring,
730 };
731debug!(?requirement, "adding closure requirement");
732 propagated_outlives_requirements.push(requirement);
733 }
734 }
735// If we succeed to promote the subject, i.e. it only contains non-local regions,
736 // and fail to prove the type test inside of the closure, the `lower_bound` has to
737 // also be at least as large as some universal region, as the type test is otherwise
738 // trivial.
739assert!(found_outlived_universal_region);
740true
741}
742743/// When we promote a type test `T: 'r`, we have to replace all region
744 /// variables in the type `T` with an equal universal region from the
745 /// closure signature.
746 /// This is not always possible, so this is a fallible process.
747x;#[instrument(level = "debug", skip(self, infcx), ret)]748fn try_promote_type_test_subject(
749&self,
750 infcx: &InferCtxt<'tcx>,
751 ty: Ty<'tcx>,
752 ) -> Option<ClosureOutlivesSubject<'tcx>> {
753let tcx = infcx.tcx;
754let mut failed = false;
755let ty = fold_regions(tcx, ty, |r, _depth| {
756let r_vid = self.to_region_vid(r);
757let r_scc = self.constraint_sccs.scc(r_vid);
758759// The challenge is this. We have some region variable `r`
760 // whose value is a set of CFG points and universal
761 // regions. We want to find if that set is *equivalent* to
762 // any of the named regions found in the closure.
763 // To do so, we simply check every candidate `u_r` for equality.
764self.scc_values
765 .universal_regions_outlived_by(r_scc)
766 .filter(|&u_r| !self.universal_regions().is_local_free_region(u_r))
767 .find(|&u_r| self.eval_equal(u_r, r_vid))
768 .map(|u_r| ty::Region::new_var(tcx, u_r))
769// In case we could not find a named region to map to,
770 // we will return `None` below.
771.unwrap_or_else(|| {
772 failed = true;
773 r
774 })
775 });
776777debug!("try_promote_type_test_subject: folded ty = {:?}", ty);
778779// This will be true if we failed to promote some region.
780if failed {
781return None;
782 }
783784Some(ClosureOutlivesSubject::Ty(ClosureOutlivesSubjectTy::bind(tcx, ty)))
785 }
786787/// Like `universal_upper_bound`, but returns an approximation more suitable
788 /// for diagnostics. If `r` contains multiple disjoint universal regions
789 /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region.
790 /// This corresponds to picking named regions over unnamed regions
791 /// (e.g. picking early-bound regions over a closure late-bound region).
792 ///
793 /// This means that the returned value may not be a true upper bound, since
794 /// only 'static is known to outlive disjoint universal regions.
795 /// Therefore, this method should only be used in diagnostic code,
796 /// where displaying *some* named universal region is better than
797 /// falling back to 'static.
798#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("approx_universal_upper_bound",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(798u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("r")
}> =
::tracing::__macro_support::FieldName::new("r");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&r)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: RegionVid = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:800",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(800u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0}",
self.region_value_str(r)) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
let mut lub = self.universal_regions().fr_fn_body;
let r_scc = self.constraint_sccs.scc(r);
let static_r = self.universal_regions().fr_static;
for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
let new_lub =
self.universal_region_relations.postdom_upper_bound(lub,
ur);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:809",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(809u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ur")
}> =
::tracing::__macro_support::FieldName::new("ur");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("lub")
}> =
::tracing::__macro_support::FieldName::new("lub");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("new_lub")
}> =
::tracing::__macro_support::FieldName::new("new_lub");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ur)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lub)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&new_lub)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
if ur != static_r && lub != static_r && new_lub == static_r {
if self.region_definition(ur).external_name.is_some() {
lub = ur;
} else if self.region_definition(lub).external_name.is_some()
{} else { lub = std::cmp::min(ur, lub); }
} else { lub = new_lub; }
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:833",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(833u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("r")
}> =
::tracing::__macro_support::FieldName::new("r");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("lub")
}> =
::tracing::__macro_support::FieldName::new("lub");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&r)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lub)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
lub
}
}
}#[instrument(level = "debug", skip(self))]799pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
800debug!("{}", self.region_value_str(r));
801802// Find the smallest universal region that contains all other
803 // universal regions within `region`.
804let mut lub = self.universal_regions().fr_fn_body;
805let r_scc = self.constraint_sccs.scc(r);
806let static_r = self.universal_regions().fr_static;
807for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
808let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
809debug!(?ur, ?lub, ?new_lub);
810// The upper bound of two non-static regions is static: this
811 // means we know nothing about the relationship between these
812 // two regions. Pick a 'better' one to use when constructing
813 // a diagnostic
814if ur != static_r && lub != static_r && new_lub == static_r {
815// Prefer the region with an `external_name` - this
816 // indicates that the region is early-bound, so working with
817 // it can produce a nicer error.
818if self.region_definition(ur).external_name.is_some() {
819 lub = ur;
820 } else if self.region_definition(lub).external_name.is_some() {
821// Leave lub unchanged
822} else {
823// If we get here, we don't have any reason to prefer
824 // one region over the other. Just pick the
825 // one with the lower index for now.
826lub = std::cmp::min(ur, lub);
827 }
828 } else {
829 lub = new_lub;
830 }
831 }
832833debug!(?r, ?lub);
834835 lub
836 }
837838/// Tests if `test` is true when applied to `lower_bound` at
839 /// `point`.
840fn eval_verify_bound(
841&self,
842 infcx: &InferCtxt<'tcx>,
843 generic_ty: Ty<'tcx>,
844 lower_bound: RegionVid,
845 verify_bound: &VerifyBound<'tcx>,
846 ) -> bool {
847{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:847",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(847u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("eval_verify_bound(lower_bound={0:?}, verify_bound={1:?})",
lower_bound, verify_bound) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);
848849match verify_bound {
850 VerifyBound::IfEq(verify_if_eq_b) => {
851self.eval_if_eq(infcx, generic_ty, lower_bound, *verify_if_eq_b)
852 }
853854 VerifyBound::IsEmpty => {
855let lower_bound_scc = self.constraint_sccs.scc(lower_bound);
856self.scc_values.elements_contained_in(lower_bound_scc).next().is_none()
857 }
858859 VerifyBound::OutlivedBy(r) => {
860let r_vid = self.to_region_vid(*r);
861self.eval_outlives(r_vid, lower_bound)
862 }
863864 VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {
865self.eval_verify_bound(infcx, generic_ty, lower_bound, verify_bound)
866 }),
867868 VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {
869self.eval_verify_bound(infcx, generic_ty, lower_bound, verify_bound)
870 }),
871 }
872 }
873874fn eval_if_eq(
875&self,
876 infcx: &InferCtxt<'tcx>,
877 generic_ty: Ty<'tcx>,
878 lower_bound: RegionVid,
879 verify_if_eq_b: ty::Binder<'tcx, VerifyIfEq<'tcx>>,
880 ) -> bool {
881let generic_ty = self.normalize_to_scc_representatives(infcx.tcx, generic_ty);
882let verify_if_eq_b = self.normalize_to_scc_representatives(infcx.tcx, verify_if_eq_b);
883match test_type_match::extract_verify_if_eq(infcx.tcx, &verify_if_eq_b, generic_ty) {
884Some(r) => {
885let r_vid = self.to_region_vid(r);
886self.eval_outlives(r_vid, lower_bound)
887 }
888None => false,
889 }
890 }
891892/// This is a conservative normalization procedure. It takes every
893 /// free region in `value` and replaces it with the
894 /// "representative" of its SCC (see `scc_representatives` field).
895 /// We are guaranteed that if two values normalize to the same
896 /// thing, then they are equal; this is a conservative check in
897 /// that they could still be equal even if they normalize to
898 /// different results. (For example, there might be two regions
899 /// with the same value that are not in the same SCC).
900 ///
901 /// N.B., this is not an ideal approach and I would like to revisit
902 /// it. However, it works pretty well in practice. In particular,
903 /// this is needed to deal with projection outlives bounds like
904 ///
905 /// ```text
906 /// <T as Foo<'0>>::Item: '1
907 /// ```
908 ///
909 /// In particular, this routine winds up being important when
910 /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
911 /// environment. In this case, if we can show that `'0 == 'a`,
912 /// and that `'b: '1`, then we know that the clause is
913 /// satisfied. In such cases, particularly due to limitations of
914 /// the trait solver =), we usually wind up with a where-clause like
915 /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
916 /// a constraint, and thus ensures that they are in the same SCC.
917 ///
918 /// So why can't we do a more correct routine? Well, we could
919 /// *almost* use the `relate_tys` code, but the way it is
920 /// currently setup it creates inference variables to deal with
921 /// higher-ranked things and so forth, and right now the inference
922 /// context is not permitted to make more inference variables. So
923 /// we use this kind of hacky solution.
924fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
925where
926T: TypeFoldable<TyCtxt<'tcx>>,
927 {
928fold_regions(tcx, value, |r, _db| {
929let vid = self.to_region_vid(r);
930let scc = self.constraint_sccs.scc(vid);
931let repr = self.scc_representative(scc);
932 ty::Region::new_var(tcx, repr)
933 })
934 }
935936/// Evaluate whether `sup_region == sub_region`.
937 ///
938 /// Panics if called before `solve()` executes,
939// This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.
940pub fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {
941self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)
942 }
943944/// Evaluate whether `sup_region: sub_region`.
945 ///
946 /// Panics if called before `solve()` executes,
947// This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.
948x;#[instrument(skip(self), level = "debug", ret)]949pub fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {
950debug!(
951"sup_region's value = {:?} universal={:?}",
952self.region_value_str(sup_region),
953self.universal_regions().is_universal_region(sup_region),
954 );
955debug!(
956"sub_region's value = {:?} universal={:?}",
957self.region_value_str(sub_region),
958self.universal_regions().is_universal_region(sub_region),
959 );
960961let sub_region_scc = self.constraint_sccs.scc(sub_region);
962let sup_region_scc = self.constraint_sccs.scc(sup_region);
963964if sub_region_scc == sup_region_scc {
965debug!("{sup_region:?}: {sub_region:?} holds trivially; they are in the same SCC");
966return true;
967 }
968969let fr_static = self.universal_regions().fr_static;
970971// If we are checking that `'sup: 'sub`, and `'sub` contains
972 // some placeholder that `'sup` cannot name, then this is only
973 // true if `'sup` outlives static.
974 //
975 // Avoid infinite recursion if `sub_region` is already `'static`
976if sub_region != fr_static
977 && !self.can_name_all_placeholders(sup_region_scc, sub_region_scc)
978 {
979debug!(
980"sub universe `{sub_region_scc:?}` is not nameable \
981 by super `{sup_region_scc:?}`, promoting to static",
982 );
983984return self.eval_outlives(sup_region, fr_static);
985 }
986987// Both the `sub_region` and `sup_region` consist of the union
988 // of some number of universal regions (along with the union
989 // of various points in the CFG; ignore those points for
990 // now). Therefore, the sup-region outlives the sub-region if,
991 // for each universal region R1 in the sub-region, there
992 // exists some region R2 in the sup-region that outlives R1.
993let universal_outlives =
994self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {
995self.scc_values
996 .universal_regions_outlived_by(sup_region_scc)
997 .any(|r2| self.universal_region_relations.outlives(r2, r1))
998 });
9991000if !universal_outlives {
1001debug!("sub region contains a universal region not present in super");
1002return false;
1003 }
10041005// Now we have to compare all the points in the sub region and make
1006 // sure they exist in the sup region.
10071008if self.universal_regions().is_universal_region(sup_region) {
1009// Micro-opt: universal regions contain all points.
1010debug!("super is universal and hence contains all points");
1011return true;
1012 }
10131014debug!("comparison between points in sup/sub");
10151016self.scc_values.contains_points(sup_region_scc, sub_region_scc)
1017 }
10181019/// Once regions have been propagated, this method is used to see
1020 /// whether any of the constraints were too strong. In particular,
1021 /// we want to check for a case where a universally quantified
1022 /// region exceeded its bounds. Consider:
1023 /// ```compile_fail
1024 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1025 /// ```
1026 /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1027 /// and hence we establish (transitively) a constraint that
1028 /// `'a: 'b`. The `propagate_constraints` code above will
1029 /// therefore add `end('a)` into the region for `'b` -- but we
1030 /// have no evidence that `'b` outlives `'a`, so we want to report
1031 /// an error.
1032 ///
1033 /// If `propagated_outlives_requirements` is `Some`, then we will
1034 /// push unsatisfied obligations into there. Otherwise, we'll
1035 /// report them as errors.
1036fn check_universal_regions(
1037&self,
1038mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1039 errors_buffer: &mut RegionErrors<'tcx>,
1040 ) {
1041for (fr, fr_definition) in self.definitions.iter_enumerated() {
1042{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1042",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1042u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fr")
}> =
::tracing::__macro_support::FieldName::new("fr");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fr_definition")
}> =
::tracing::__macro_support::FieldName::new("fr_definition");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr_definition)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?fr, ?fr_definition);
1043match fr_definition.origin {
1044 NllRegionVariableOrigin::FreeRegion => {
1045// Go through each of the universal regions `fr` and check that
1046 // they did not grow too large, accumulating any requirements
1047 // for our caller into the `outlives_requirements` vector.
1048self.check_universal_region(
1049 fr,
1050&mut propagated_outlives_requirements,
1051 errors_buffer,
1052 );
1053 }
10541055 NllRegionVariableOrigin::Placeholder(placeholder) => {
1056self.check_bound_universal_region(fr, placeholder, errors_buffer);
1057 }
10581059 NllRegionVariableOrigin::Existential { .. } => {
1060// nothing to check here
1061}
1062 }
1063 }
1064 }
10651066/// Checks if Polonius has found any unexpected free region relations.
1067 ///
1068 /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent
1069 /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`
1070 /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL
1071 /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.
1072 ///
1073 /// More details can be found in this blog post by Niko:
1074 /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/>
1075 ///
1076 /// In the canonical example
1077 /// ```compile_fail
1078 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1079 /// ```
1080 /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a
1081 /// constraint that `'a: 'b`. It is an error that we have no evidence that this
1082 /// constraint holds.
1083 ///
1084 /// If `propagated_outlives_requirements` is `Some`, then we will
1085 /// push unsatisfied obligations into there. Otherwise, we'll
1086 /// report them as errors.
1087fn check_polonius_subset_errors(
1088&self,
1089mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1090 errors_buffer: &mut RegionErrors<'tcx>,
1091 polonius_output: &PoloniusOutput,
1092 ) {
1093{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1093",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1093u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_polonius_subset_errors: {0} subset_errors",
polonius_output.subset_errors.len()) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1094"check_polonius_subset_errors: {} subset_errors",
1095 polonius_output.subset_errors.len()
1096 );
10971098// Similarly to `check_universal_regions`: a free region relation, which was not explicitly
1099 // declared ("known") was found by Polonius, so emit an error, or propagate the
1100 // requirements for our caller into the `propagated_outlives_requirements` vector.
1101 //
1102 // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the
1103 // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with
1104 // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",
1105 // and the "superset origin" is the outlived "shorter free region".
1106 //
1107 // Note: Polonius will produce a subset error at every point where the unexpected
1108 // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful
1109 // for diagnostics in the future, e.g. to point more precisely at the key locations
1110 // requiring this constraint to hold. However, the error and diagnostics code downstream
1111 // expects that these errors are not duplicated (and that they are in a certain order).
1112 // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or
1113 // anonymous lifetimes for example, could give these names differently, while others like
1114 // the outlives suggestions or the debug output from `#[rustc_regions]` would be
1115 // duplicated. The polonius subset errors are deduplicated here, while keeping the
1116 // CFG-location ordering.
1117 // We can iterate the HashMap here because the result is sorted afterwards.
1118#[allow(rustc::potential_query_instability)]
1119let mut subset_errors: Vec<_> = polonius_output1120 .subset_errors
1121 .iter()
1122 .flat_map(|(_location, subset_errors)| subset_errors.iter())
1123 .collect();
1124subset_errors.sort();
1125subset_errors.dedup();
11261127for &(longer_fr, shorter_fr) in subset_errors.into_iter() {
1128{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1128",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1128u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_polonius_subset_errors: subset_error longer_fr={0:?},shorter_fr={1:?}",
longer_fr, shorter_fr) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1129"check_polonius_subset_errors: subset_error longer_fr={:?},\
1130 shorter_fr={:?}",
1131 longer_fr, shorter_fr
1132 );
11331134let propagated = self.try_propagate_universal_region_error(
1135 longer_fr.into(),
1136 shorter_fr.into(),
1137&mut propagated_outlives_requirements,
1138 );
1139if propagated == RegionRelationCheckResult::Error {
1140 errors_buffer.push(RegionErrorKind::RegionError {
1141 longer_fr: longer_fr.into(),
1142 shorter_fr: shorter_fr.into(),
1143 fr_origin: NllRegionVariableOrigin::FreeRegion,
1144 is_reported: true,
1145 });
1146 }
1147 }
11481149// Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has
1150 // a more complete picture on how to separate this responsibility.
1151for (fr, fr_definition) in self.definitions.iter_enumerated() {
1152match fr_definition.origin {
1153 NllRegionVariableOrigin::FreeRegion => {
1154// handled by polonius above
1155}
11561157 NllRegionVariableOrigin::Placeholder(placeholder) => {
1158self.check_bound_universal_region(fr, placeholder, errors_buffer);
1159 }
11601161 NllRegionVariableOrigin::Existential { .. } => {
1162// nothing to check here
1163}
1164 }
1165 }
1166 }
11671168/// The largest universe of any region nameable from this SCC.
1169fn max_nameable_universe(&self, scc: ConstraintSccIndex) -> UniverseIndex {
1170self.scc_annotations[scc].max_nameable_universe()
1171 }
11721173/// Checks the final value for the free region `fr` to see if it
1174 /// grew too large. In particular, examine what `end(X)` points
1175 /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1176 /// fr`, we want to check that `fr: X`. If not, that's either an
1177 /// error, or something we have to propagate to our creator.
1178 ///
1179 /// Things that are to be propagated are accumulated into the
1180 /// `outlives_requirements` vector.
1181#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_universal_region",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1181u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("longer_fr")
}> =
::tracing::__macro_support::FieldName::new("longer_fr");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&longer_fr)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
if !self.max_nameable_universe(longer_fr_scc).is_root() {
::core::panicking::panic("assertion failed: self.max_nameable_universe(longer_fr_scc).is_root()")
};
let representative = self.scc_representative(longer_fr_scc);
if representative != longer_fr {
if let RegionRelationCheckResult::Error =
self.check_universal_region_relation(longer_fr,
representative, propagated_outlives_requirements) {
errors_buffer.push(RegionErrorKind::RegionError {
longer_fr,
shorter_fr: representative,
fr_origin: NllRegionVariableOrigin::FreeRegion,
is_reported: true,
});
}
return;
}
let mut error_reported = false;
for shorter_fr in
self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
if let RegionRelationCheckResult::Error =
self.check_universal_region_relation(longer_fr, shorter_fr,
propagated_outlives_requirements) {
errors_buffer.push(RegionErrorKind::RegionError {
longer_fr,
shorter_fr,
fr_origin: NllRegionVariableOrigin::FreeRegion,
is_reported: !error_reported,
});
error_reported = true;
}
}
}
}
}#[instrument(skip(self, propagated_outlives_requirements, errors_buffer), level = "debug")]1182fn check_universal_region(
1183&self,
1184 longer_fr: RegionVid,
1185 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1186 errors_buffer: &mut RegionErrors<'tcx>,
1187 ) {
1188let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
11891190// Because this free region must be in the ROOT universe, we
1191 // know it cannot contain any bound universes.
1192assert!(self.max_nameable_universe(longer_fr_scc).is_root());
11931194// Only check all of the relations for the main representative of each
1195 // SCC, otherwise just check that we outlive said representative. This
1196 // reduces the number of redundant relations propagated out of
1197 // closures.
1198 // Note that the representative will be a universal region if there is
1199 // one in this SCC, so we will always check the representative here.
1200let representative = self.scc_representative(longer_fr_scc);
1201if representative != longer_fr {
1202if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1203 longer_fr,
1204 representative,
1205 propagated_outlives_requirements,
1206 ) {
1207 errors_buffer.push(RegionErrorKind::RegionError {
1208 longer_fr,
1209 shorter_fr: representative,
1210 fr_origin: NllRegionVariableOrigin::FreeRegion,
1211 is_reported: true,
1212 });
1213 }
1214return;
1215 }
12161217// Find every region `o` such that `fr: o`
1218 // (because `fr` includes `end(o)`).
1219let mut error_reported = false;
1220for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
1221if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1222 longer_fr,
1223 shorter_fr,
1224 propagated_outlives_requirements,
1225 ) {
1226// We only report the first region error. Subsequent errors are hidden so as
1227 // not to overwhelm the user, but we do record them so as to potentially print
1228 // better diagnostics elsewhere...
1229errors_buffer.push(RegionErrorKind::RegionError {
1230 longer_fr,
1231 shorter_fr,
1232 fr_origin: NllRegionVariableOrigin::FreeRegion,
1233 is_reported: !error_reported,
1234 });
12351236 error_reported = true;
1237 }
1238 }
1239 }
12401241/// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate
1242 /// the constraint outward (e.g. to a closure environment), but if that fails, there is an
1243 /// error.
1244fn check_universal_region_relation(
1245&self,
1246 longer_fr: RegionVid,
1247 shorter_fr: RegionVid,
1248 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1249 ) -> RegionRelationCheckResult {
1250// If it is known that `fr: o`, carry on.
1251if self.universal_region_relations.outlives(longer_fr, shorter_fr) {
1252 RegionRelationCheckResult::Ok1253 } else {
1254// If we are not in a context where we can't propagate errors, or we
1255 // could not shrink `fr` to something smaller, then just report an
1256 // error.
1257 //
1258 // Note: in this case, we use the unapproximated regions to report the
1259 // error. This gives better error messages in some cases.
1260self.try_propagate_universal_region_error(
1261longer_fr,
1262shorter_fr,
1263propagated_outlives_requirements,
1264 )
1265 }
1266 }
12671268/// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's
1269 /// creator. If we cannot, then the caller should report an error to the user.
1270fn try_propagate_universal_region_error(
1271&self,
1272 longer_fr: RegionVid,
1273 shorter_fr: RegionVid,
1274 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1275 ) -> RegionRelationCheckResult {
1276if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {
1277// Shrink `longer_fr` until we find some non-local regions.
1278 // We'll call them `longer_fr-` -- they are ever so slightly smaller than
1279 // `longer_fr`.
1280let longer_fr_minus = self.universal_region_relations.non_local_lower_bounds(longer_fr);
12811282{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1282",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1282u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("try_propagate_universal_region_error: fr_minus={0:?}",
longer_fr_minus) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("try_propagate_universal_region_error: fr_minus={:?}", longer_fr_minus);
12831284// If we don't find a any non-local regions, we should error out as there is nothing
1285 // to propagate.
1286if longer_fr_minus.is_empty() {
1287return RegionRelationCheckResult::Error;
1288 }
12891290let best_blame = self.best_blame_constraint(
1291longer_fr,
1292 NllRegionVariableOrigin::FreeRegion,
1293shorter_fr,
1294 );
1295let OutlivesConstraint { category, span, .. } = best_blame.constraint();
12961297// Grow `shorter_fr` until we find some non-local regions.
1298 // We will always find at least one: `'static`. We'll call
1299 // them `shorter_fr+` -- they're ever so slightly larger
1300 // than `shorter_fr`.
1301let shorter_fr_plus =
1302self.universal_region_relations.non_local_upper_bounds(shorter_fr);
1303{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1303",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1303u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("try_propagate_universal_region_error: shorter_fr_plus={0:?}",
shorter_fr_plus) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("try_propagate_universal_region_error: shorter_fr_plus={:?}", shorter_fr_plus);
13041305// We then create constraints `longer_fr-: shorter_fr+` that may or may not
1306 // be propagated (see below).
1307let mut constraints = ::alloc::vec::Vec::new()vec![];
1308for fr_minus in longer_fr_minus {
1309for shorter_fr_plus in &shorter_fr_plus {
1310 constraints.push((fr_minus, *shorter_fr_plus));
1311 }
1312 }
13131314// We only need to propagate at least one of the constraints for
1315 // soundness. However, we want to avoid arbitrary choices here
1316 // and currently don't support returning OR constraints.
1317 //
1318 // If any of the `shorter_fr+` regions are already outlived by `longer_fr-`,
1319 // we propagate only those.
1320 //
1321 // Consider this example (`'b: 'a` == `a -> b`), where we try to propagate `'d: 'a`:
1322 // a --> b --> d
1323 // \
1324 // \-> c
1325 // Here, `shorter_fr+` of `'a` == `['b, 'c]`.
1326 // Propagating `'d: 'b` is correct and should occur; `'d: 'c` is redundant because of
1327 // `'d: 'b` and could reject valid code.
1328 //
1329 // So we filter the constraints to regions already outlived by `longer_fr-`, but if
1330 // the filter yields an empty set, we fall back to the original one.
1331let subset: Vec<_> = constraints1332 .iter()
1333 .filter(|&&(fr_minus, shorter_fr_plus)| {
1334self.eval_outlives(fr_minus, shorter_fr_plus)
1335 })
1336 .copied()
1337 .collect();
1338let propagated_constraints = if subset.is_empty() { constraints } else { subset };
1339{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1339",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1339u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("try_propagate_universal_region_error: constraints={0:?}",
propagated_constraints) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1340"try_propagate_universal_region_error: constraints={:?}",
1341 propagated_constraints
1342 );
13431344if !!propagated_constraints.is_empty() {
{
::core::panicking::panic_fmt(format_args!("Expected at least one constraint to propagate here"));
}
};assert!(
1345 !propagated_constraints.is_empty(),
1346"Expected at least one constraint to propagate here"
1347);
13481349for (fr_minus, fr_plus) in propagated_constraints {
1350// Push the constraint `long_fr-: shorter_fr+`
1351propagated_outlives_requirements.push(ClosureOutlivesRequirement {
1352 subject: ClosureOutlivesSubject::Region(fr_minus),
1353 outlived_free_region: fr_plus,
1354 blame_span: *span,
1355 category: *category,
1356 });
1357 }
1358return RegionRelationCheckResult::Propagated;
1359 }
13601361 RegionRelationCheckResult::Error1362 }
13631364fn check_bound_universal_region(
1365&self,
1366 longer_fr: RegionVid,
1367 placeholder: ty::PlaceholderRegion<'tcx>,
1368 errors_buffer: &mut RegionErrors<'tcx>,
1369 ) {
1370{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1370",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1370u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_bound_universal_region(fr={0:?}, placeholder={1:?})",
longer_fr, placeholder) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);
13711372let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1373{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1373",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1373u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_bound_universal_region: longer_fr_scc={0:?}",
longer_fr_scc) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);
13741375// If we have some bound universal region `'a`, then the only
1376 // elements it can contain is itself -- we don't know anything
1377 // else about it!
1378if let Some(error_element) = self1379 .scc_values
1380 .elements_contained_in(longer_fr_scc)
1381 .find(|e| *e != RegionElement::PlaceholderRegion(placeholder))
1382 {
1383let illegally_outlived_r = self.region_from_element(longer_fr, &error_element);
1384// Stop after the first error, it gets too noisy otherwise, and does not provide more information.
1385errors_buffer.push(RegionErrorKind::PlaceholderOutlivesIllegalRegion {
1386longer_fr,
1387illegally_outlived_r,
1388 });
1389 } else {
1390{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1390",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1390u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_bound_universal_region: all bounds satisfied")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_bound_universal_region: all bounds satisfied");
1391 }
1392 }
13931394pub(crate) fn constraint_path_between_regions(
1395&self,
1396 from_region: RegionVid,
1397 to_region: RegionVid,
1398 ) -> Option<Vec<OutlivesConstraint<'tcx>>> {
1399if from_region == to_region {
1400::rustc_middle::util::bug::bug_fmt(format_args!("Tried to find a path between {0:?} and itself!",
from_region));bug!("Tried to find a path between {from_region:?} and itself!");
1401 }
1402self.constraint_path_to(from_region, |to| to == to_region, true).map(|o| o.0)
1403 }
14041405/// Walks the graph of constraints (where `'a: 'b` is considered
1406 /// an edge `'a -> 'b`) to find a path from `from_region` to
1407 /// `to_region`.
1408 ///
1409 /// Returns: a series of constraints as well as the region `R`
1410 /// that passed the target test.
1411 /// If `include_static_outlives_all` is `true`, then the synthetic
1412 /// outlives constraints `'static -> a` for every region `a` are
1413 /// considered in the search, otherwise they are ignored.
1414x;#[instrument(skip(self, target_test), ret)]1415pub(crate) fn constraint_path_to(
1416&self,
1417 from_region: RegionVid,
1418 target_test: impl Fn(RegionVid) -> bool,
1419 include_placeholder_static: bool,
1420 ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {
1421self.find_constraint_path_between_regions_inner(
1422true,
1423 from_region,
1424&target_test,
1425 include_placeholder_static,
1426 )
1427 .or_else(|| {
1428self.find_constraint_path_between_regions_inner(
1429false,
1430 from_region,
1431&target_test,
1432 include_placeholder_static,
1433 )
1434 })
1435 }
14361437/// The constraints we get from equating the hidden type of each use of an opaque
1438 /// with its final hidden type may end up getting preferred over other, potentially
1439 /// longer constraint paths.
1440 ///
1441 /// Given that we compute the final hidden type by relying on this existing constraint
1442 /// path, this can easily end up hiding the actual reason for why we require these regions
1443 /// to be equal.
1444 ///
1445 /// To handle this, we first look at the path while ignoring these constraints and then
1446 /// retry while considering them. This is not perfect, as the `from_region` may have already
1447 /// been partially related to its argument region, so while we rely on a member constraint
1448 /// to get a complete path, the most relevant step of that path already existed before then.
1449fn find_constraint_path_between_regions_inner(
1450&self,
1451 ignore_opaque_type_constraints: bool,
1452 from_region: RegionVid,
1453 target_test: impl Fn(RegionVid) -> bool,
1454 include_placeholder_static: bool,
1455 ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {
1456let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);
1457context[from_region] = Trace::StartRegion;
14581459let fr_static = self.universal_regions().fr_static;
14601461// Use a deque so that we do a breadth-first search. We will
1462 // stop at the first match, which ought to be the shortest
1463 // path (fewest constraints).
1464let mut deque = VecDeque::new();
1465deque.push_back(from_region);
14661467while let Some(r) = deque.pop_front() {
1468{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1468",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1468u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("constraint_path_to: from_region={0:?} r={1:?} value={2}",
from_region, r, self.region_value_str(r)) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1469"constraint_path_to: from_region={:?} r={:?} value={}",
1470 from_region,
1471 r,
1472self.region_value_str(r),
1473 );
14741475// Check if we reached the region we were looking for. If so,
1476 // we can reconstruct the path that led to it and return it.
1477if target_test(r) {
1478let mut result = ::alloc::vec::Vec::new()vec![];
1479let mut p = r;
1480// This loop is cold and runs at the end, which is why we delay
1481 // `OutlivesConstraint` construction until now.
1482loop {
1483match context[p] {
1484 Trace::FromGraph(c) => {
1485 p = c.sup;
1486 result.push(*c);
1487 }
14881489 Trace::FromStatic(sub) => {
1490let c = OutlivesConstraint {
1491 sup: fr_static,
1492 sub,
1493 locations: Locations::All(DUMMY_SP),
1494 span: DUMMY_SP,
1495 category: ConstraintCategory::Internal,
1496 variance_info: ty::VarianceDiagInfo::default(),
1497 from_closure: false,
1498 };
1499 p = c.sup;
1500 result.push(c);
1501 }
15021503 Trace::StartRegion => {
1504 result.reverse();
1505return Some((result, r));
1506 }
15071508 Trace::NotVisited => {
1509::rustc_middle::util::bug::bug_fmt(format_args!("found unvisited region {0:?} on path to {1:?}",
p, r))bug!("found unvisited region {:?} on path to {:?}", p, r)1510 }
1511 }
1512 }
1513 }
15141515// Otherwise, walk over the outgoing constraints and
1516 // enqueue any regions we find, keeping track of how we
1517 // reached them.
15181519 // A constraint like `'r: 'x` can come from our constraint
1520 // graph.
15211522 // Always inline this closure because it can be hot.
1523let mut handle_trace = #[inline(always)]
1524|sub, trace| {
1525if let Trace::NotVisited = context[sub] {
1526 context[sub] = trace;
1527 deque.push_back(sub);
1528 }
1529 };
15301531// If this is the `'static` region and the graph's direction is normal, then set up the
1532 // Edges iterator to return all regions (#53178).
1533if r == fr_static && self.constraint_graph.is_normal() {
1534for sub in self.constraint_graph.outgoing_edges_from_static() {
1535 handle_trace(sub, Trace::FromStatic(sub));
1536 }
1537 } else {
1538let edges = self.constraint_graph.outgoing_edges_from_graph(r, &self.constraints);
1539// This loop can be hot.
1540for constraint in edges {
1541match constraint.category {
1542 ConstraintCategory::OutlivesUnnameablePlaceholder(_)
1543if !include_placeholder_static =>
1544 {
1545{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1545",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1545u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Ignoring illegal placeholder constraint: {0:?}",
constraint) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("Ignoring illegal placeholder constraint: {constraint:?}");
1546continue;
1547 }
1548 ConstraintCategory::OpaqueType if ignore_opaque_type_constraints => {
1549{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1549",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1549u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Ignoring member constraint: {0:?}",
constraint) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("Ignoring member constraint: {constraint:?}");
1550continue;
1551 }
1552_ => {}
1553 }
15541555if true {
{
match (&constraint.sup, &r) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(constraint.sup, r);
1556 handle_trace(constraint.sub, Trace::FromGraph(constraint));
1557 }
1558 }
1559 }
15601561None1562 }
15631564/// Finds some region R such that `fr1: R` and `R` is live at `location`.
1565x;#[instrument(skip(self), level = "trace", ret)]1566pub(crate) fn find_sub_region_live_at(&self, fr1: RegionVid, location: Location) -> RegionVid {
1567trace!(scc = ?self.constraint_sccs.scc(fr1));
1568trace!(universe = ?self.max_nameable_universe(self.constraint_sccs.scc(fr1)));
1569self.constraint_path_to(fr1, |r| {
1570trace!(?r, liveness_constraints=?self.liveness_constraints.pretty_print_live_points(r));
1571self.liveness_constraints.is_live_at(r, location)
1572 }, true).unwrap().1
1573}
15741575/// Get the region outlived by `longer_fr` and live at `element`.
1576fn region_from_element(
1577&self,
1578 longer_fr: RegionVid,
1579 element: &RegionElement<'tcx>,
1580 ) -> RegionVid {
1581match *element {
1582 RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
1583 RegionElement::RootUniversalRegion(r) => r,
1584 RegionElement::PlaceholderRegion(error_placeholder) => self1585 .definitions
1586 .iter_enumerated()
1587 .find_map(|(r, definition)| match definition.origin {
1588 NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
1589_ => None,
1590 })
1591 .unwrap(),
1592 }
1593 }
15941595/// Get the region definition of `r`.
1596pub(crate) fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> {
1597&self.definitions[r]
1598 }
15991600/// Check if the SCC of `r` contains `upper`, a free region.
1601pub(crate) fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool {
1602let r_scc = self.constraint_sccs.scc(r);
1603self.scc_values.contains_free_region(r_scc, upper)
1604 }
16051606pub(crate) fn universal_regions(&self) -> &UniversalRegions<'tcx> {
1607&self.universal_region_relations.universal_regions
1608 }
16091610/// Tries to find the best constraint to blame for the fact that
1611 /// `R: from_region`, where `R` is some region that meets
1612 /// `target_test`. This works by following the constraint graph,
1613 /// creating a constraint path that forces `R` to outlive
1614 /// `from_region`, and then finding the best choices within that
1615 /// path to blame.
1616#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("best_blame_constraint",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1616u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("from_region")
}> =
::tracing::__macro_support::FieldName::new("from_region");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("from_region_origin")
}> =
::tracing::__macro_support::FieldName::new("from_region_origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("to_region")
}> =
::tracing::__macro_support::FieldName::new("to_region");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&from_region)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&from_region_origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&to_region)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: BestBlame<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
if !(from_region != to_region) {
{
::core::panicking::panic_fmt(format_args!("Trying to blame a region for itself!"));
}
};
let path =
self.constraint_path_between_regions(from_region,
to_region).unwrap();
let due_to_placeholder_outlives =
path.iter().find_map(|c|
{
if let ConstraintCategory::OutlivesUnnameablePlaceholder(unnameable)
= c.category {
Some(unnameable)
} else { None }
});
let mut path =
if let Some(unnameable) = due_to_placeholder_outlives &&
unnameable != from_region {
self.constraint_path_to(from_region, |r| r == unnameable,
false).unwrap().0
} else { path };
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1648",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1648u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("path={0:#?}",
path.iter().map(|c|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?} ({1:?}: {2:?})", c,
self.constraint_sccs.scc(c.sup),
self.constraint_sccs.scc(c.sub)))
})).collect::<Vec<_>>()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let blame_source =
match from_region_origin {
NllRegionVariableOrigin::FreeRegion => true,
NllRegionVariableOrigin::Placeholder(_) => false,
NllRegionVariableOrigin::Existential { name: _ } => {
{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("existentials can outlive everything")));
}
}
};
let constraint_interest =
|constraint: &OutlivesConstraint<'tcx>|
{
let category =
if let Some(kind) = constraint.span.desugaring_kind() &&
(kind != DesugaringKind::QuestionMark ||
!#[allow(non_exhaustive_omitted_patterns)] match constraint.category
{
ConstraintCategory::Return(_) => true,
_ => false,
}) {
ConstraintCategory::Boring
} else { constraint.category };
let interest =
match category {
ConstraintCategory::Return(_) => 0,
ConstraintCategory::Cast {
is_raw_ptr_dyn_type_cast: _,
unsize_to: Some(unsize_ty),
is_implicit_coercion: true } if
to_region == self.universal_regions().fr_static &&
let ty::Adt(_, args) = unsize_ty.kind() &&
args.iter().any(|arg|
arg.as_type().is_some_and(|ty| ty.is_trait())) &&
!path.iter().any(|c|
#[allow(non_exhaustive_omitted_patterns)] match c.category {
ConstraintCategory::TypeAnnotation(_) => true,
_ => false,
}) => {
1
}
ConstraintCategory::Yield | ConstraintCategory::UseAsConst |
ConstraintCategory::UseAsStatic |
ConstraintCategory::TypeAnnotation(AnnotationSource::Ascription
| AnnotationSource::Declaration |
AnnotationSource::OpaqueCast) | ConstraintCategory::Cast {
.. } | ConstraintCategory::CallArgument(_) |
ConstraintCategory::CopyBound |
ConstraintCategory::SizedBound |
ConstraintCategory::Assignment | ConstraintCategory::Usage |
ConstraintCategory::ClosureUpvar(_) => 2,
ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg)
=> 3,
ConstraintCategory::Predicate(_) |
ConstraintCategory::OpaqueType => 4,
ConstraintCategory::Boring => 5,
ConstraintCategory::BoringNoLocation => 6,
ConstraintCategory::Internal => 7,
ConstraintCategory::OutlivesUnnameablePlaceholder(_) => 8,
ConstraintCategory::SolverRegionConstraint(_) => 9,
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1782",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1782u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("constraint {0:?} category: {1:?}, interest: {2:?}",
constraint, category, interest) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
interest
};
let best_choice =
if blame_source {
path.iter().enumerate().rev().min_by_key(|(_, c)|
constraint_interest(c)).unwrap().0
} else {
path.iter().enumerate().min_by_key(|(_, c)|
constraint_interest(c)).unwrap().0
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/region_infer/mod.rs:1793",
"rustc_borrowck::region_infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/region_infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1793u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::region_infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("best_choice")
}> =
::tracing::__macro_support::FieldName::new("best_choice");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("blame_source")
}> =
::tracing::__macro_support::FieldName::new("blame_source");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&best_choice)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&blame_source)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let best_blame_idx =
if let Some(next) = path.get(best_choice + 1) &&
#[allow(non_exhaustive_omitted_patterns)] match path[best_choice].category
{
ConstraintCategory::Return(_) => true,
_ => false,
} && next.category == ConstraintCategory::OpaqueType {
best_choice + 1
} else if path[best_choice].category ==
ConstraintCategory::Return(ReturnConstraint::Normal) &&
let Some(field) =
path.iter().find_map(|p|
{
if let ConstraintCategory::ClosureUpvar(f) = p.category {
Some(f)
} else { None }
}) {
path[best_choice].category =
ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field));
best_choice
} else { best_choice };
if !!#[allow(non_exhaustive_omitted_patterns)] match path[best_blame_idx].category
{
ConstraintCategory::OutlivesUnnameablePlaceholder(_) =>
true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("Illegal placeholder constraint blamed; should have redirected to other region relation"));
}
};
BestBlame { path, idx: best_blame_idx }
}
}
}#[instrument(level = "debug", skip(self))]1617pub(crate) fn best_blame_constraint(
1618&self,
1619 from_region: RegionVid,
1620 from_region_origin: NllRegionVariableOrigin<'tcx>,
1621 to_region: RegionVid,
1622 ) -> BestBlame<'tcx> {
1623assert!(from_region != to_region, "Trying to blame a region for itself!");
16241625let path = self.constraint_path_between_regions(from_region, to_region).unwrap();
16261627// If we are passing through a constraint added because we reached an unnameable placeholder `'unnameable`,
1628 // redirect search towards `'unnameable`.
1629let due_to_placeholder_outlives = path.iter().find_map(|c| {
1630if let ConstraintCategory::OutlivesUnnameablePlaceholder(unnameable) = c.category {
1631Some(unnameable)
1632 } else {
1633None
1634}
1635 });
16361637// Edge case: it's possible that `'from_region` is an unnameable placeholder.
1638let mut path = if let Some(unnameable) = due_to_placeholder_outlives
1639 && unnameable != from_region
1640 {
1641// We ignore the extra edges due to unnameable placeholders to get
1642 // an explanation that was present in the original constraint graph.
1643self.constraint_path_to(from_region, |r| r == unnameable, false).unwrap().0
1644} else {
1645 path
1646 };
16471648debug!(
1649"path={:#?}",
1650 path.iter()
1651 .map(|c| format!(
1652"{:?} ({:?}: {:?})",
1653 c,
1654self.constraint_sccs.scc(c.sup),
1655self.constraint_sccs.scc(c.sub),
1656 ))
1657 .collect::<Vec<_>>()
1658 );
16591660// When reporting an error, there is typically a chain of constraints leading from some
1661 // "source" region which must outlive some "target" region.
1662 // In most cases, we prefer to "blame" the constraints closer to the target --
1663 // but there is one exception. When constraints arise from higher-ranked subtyping,
1664 // we generally prefer to blame the source value,
1665 // as the "target" in this case tends to be some type annotation that the user gave.
1666 // Therefore, if we find that the region origin is some instantiation
1667 // of a higher-ranked region, we start our search from the "source" point
1668 // rather than the "target", and we also tweak a few other things.
1669 //
1670 // An example might be this bit of Rust code:
1671 //
1672 // ```rust
1673 // let x: fn(&'static ()) = |_| {};
1674 // let y: for<'a> fn(&'a ()) = x;
1675 // ```
1676 //
1677 // In MIR, this will be converted into a combination of assignments and type ascriptions.
1678 // In particular, the 'static is imposed through a type ascription:
1679 //
1680 // ```rust
1681 // x = ...;
1682 // AscribeUserType(x, fn(&'static ())
1683 // y = x;
1684 // ```
1685 //
1686 // We wind up ultimately with constraints like
1687 //
1688 // ```rust
1689 // !a: 'temp1 // from the `y = x` statement
1690 // 'temp1: 'temp2
1691 // 'temp2: 'static // from the AscribeUserType
1692 // ```
1693 //
1694 // and here we prefer to blame the source (the y = x statement).
1695let blame_source = match from_region_origin {
1696 NllRegionVariableOrigin::FreeRegion => true,
1697 NllRegionVariableOrigin::Placeholder(_) => false,
1698// `'existential: 'whatever` never results in a region error by itself.
1699 // We may always infer it to `'static` afterall. This means while an error
1700 // path may go through an existential, these existentials are never the
1701 // `from_region`.
1702NllRegionVariableOrigin::Existential { name: _ } => {
1703unreachable!("existentials can outlive everything")
1704 }
1705 };
17061707// To pick a constraint to blame, we organize constraints by how interesting we expect them
1708 // to be in diagnostics, then pick the most interesting one closest to either the source or
1709 // the target on our constraint path.
1710let constraint_interest = |constraint: &OutlivesConstraint<'tcx>| {
1711// Try to avoid blaming constraints from desugarings, since they may not clearly match
1712 // match what users have written. As an exception, allow blaming returns generated by
1713 // `?` desugaring, since the correspondence is fairly clear.
1714let category = if let Some(kind) = constraint.span.desugaring_kind()
1715 && (kind != DesugaringKind::QuestionMark
1716 || !matches!(constraint.category, ConstraintCategory::Return(_)))
1717 {
1718 ConstraintCategory::Boring
1719 } else {
1720 constraint.category
1721 };
17221723let interest = match category {
1724// Returns usually provide a type to blame and have specially written diagnostics,
1725 // so prioritize them.
1726ConstraintCategory::Return(_) => 0,
1727// Unsizing coercions are interesting, since we have a note for that:
1728 // `BorrowExplanation::add_object_lifetime_default_note`.
1729 // FIXME(dianne): That note shouldn't depend on a coercion being blamed; see issue
1730 // #131008 for an example of where we currently don't emit it but should.
1731 // Once the note is handled properly, this case should be removed. Until then, it
1732 // should be as limited as possible; the note is prone to false positives and this
1733 // constraint usually isn't best to blame.
1734ConstraintCategory::Cast {
1735 is_raw_ptr_dyn_type_cast: _,
1736 unsize_to: Some(unsize_ty),
1737 is_implicit_coercion: true,
1738 } if to_region == self.universal_regions().fr_static
1739// Mirror the note's condition, to minimize how often this diverts blame.
1740&& let ty::Adt(_, args) = unsize_ty.kind()
1741 && args.iter().any(|arg| arg.as_type().is_some_and(|ty| ty.is_trait()))
1742// Mimic old logic for this, to minimize false positives in tests.
1743&& !path
1744 .iter()
1745 .any(|c| matches!(c.category, ConstraintCategory::TypeAnnotation(_))) =>
1746 {
17471
1748}
1749// Between other interesting constraints, order by their position on the `path`.
1750ConstraintCategory::Yield
1751 | ConstraintCategory::UseAsConst
1752 | ConstraintCategory::UseAsStatic
1753 | ConstraintCategory::TypeAnnotation(
1754 AnnotationSource::Ascription
1755 | AnnotationSource::Declaration
1756 | AnnotationSource::OpaqueCast,
1757 )
1758 | ConstraintCategory::Cast { .. }
1759 | ConstraintCategory::CallArgument(_)
1760 | ConstraintCategory::CopyBound
1761 | ConstraintCategory::SizedBound
1762 | ConstraintCategory::Assignment
1763 | ConstraintCategory::Usage
1764 | ConstraintCategory::ClosureUpvar(_) => 2,
1765// Generic arguments are unlikely to be what relates regions together
1766ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg) => 3,
1767// We handle predicates and opaque types specially; don't prioritize them here.
1768ConstraintCategory::Predicate(_) | ConstraintCategory::OpaqueType => 4,
1769// `Boring` constraints can correspond to user-written code and have useful spans,
1770 // but don't provide any other useful information for diagnostics.
1771ConstraintCategory::Boring => 5,
1772// `BoringNoLocation` constraints can point to user-written code, but are less
1773 // specific, and are not used for relations that would make sense to blame.
1774ConstraintCategory::BoringNoLocation => 6,
1775// Do not blame internal constraints if we can avoid it. Never blame
1776 // the `'region: 'static` constraints introduced by placeholder outlives.
1777ConstraintCategory::Internal => 7,
1778 ConstraintCategory::OutlivesUnnameablePlaceholder(_) => 8,
1779 ConstraintCategory::SolverRegionConstraint(_) => 9,
1780 };
17811782debug!("constraint {constraint:?} category: {category:?}, interest: {interest:?}");
17831784 interest
1785 };
17861787let best_choice = if blame_source {
1788 path.iter().enumerate().rev().min_by_key(|(_, c)| constraint_interest(c)).unwrap().0
1789} else {
1790 path.iter().enumerate().min_by_key(|(_, c)| constraint_interest(c)).unwrap().0
1791};
17921793debug!(?best_choice, ?blame_source);
17941795let best_blame_idx = if let Some(next) = path.get(best_choice + 1)
1796 && matches!(path[best_choice].category, ConstraintCategory::Return(_))
1797 && next.category == ConstraintCategory::OpaqueType
1798 {
1799// The return expression is being influenced by the return type being
1800 // impl Trait, point at the return type and not the return expr.
1801best_choice + 1
1802} else if path[best_choice].category == ConstraintCategory::Return(ReturnConstraint::Normal)
1803 && let Some(field) = path.iter().find_map(|p| {
1804if let ConstraintCategory::ClosureUpvar(f) = p.category { Some(f) } else { None }
1805 })
1806 {
1807 path[best_choice].category =
1808 ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field));
1809 best_choice
1810 } else {
1811 best_choice
1812 };
18131814assert!(
1815 !matches!(
1816 path[best_blame_idx].category,
1817 ConstraintCategory::OutlivesUnnameablePlaceholder(_)
1818 ),
1819"Illegal placeholder constraint blamed; should have redirected to other region relation"
1820);
18211822 BestBlame { path, idx: best_blame_idx }
1823 }
18241825pub(crate) fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
1826// Query canonicalization can create local superuniverses (for example in
1827 // `InferCtx::query_response_instantiation_guess`), but they don't have an associated
1828 // `UniverseInfo` explaining why they were created.
1829 // This can cause ICEs if these causes are accessed in diagnostics, for example in issue
1830 // #114907 where this happens via liveness and dropck outlives results.
1831 // Therefore, we return a default value in case that happens, which should at worst emit a
1832 // suboptimal error, instead of the ICE.
1833self.universe_causes.get(&universe).cloned().unwrap_or_else(UniverseInfo::other)
1834 }
18351836/// Tries to find the terminator of the loop in which the region 'r' resides.
1837 /// Returns the location of the terminator if found.
1838pub(crate) fn find_loop_terminator_location(
1839&self,
1840 r: RegionVid,
1841 body: &Body<'_>,
1842 ) -> Option<Location> {
1843let scc = self.constraint_sccs.scc(r);
1844let locations = self.scc_values.locations_outlived_by(scc);
1845for location in locations {
1846let bb = &body[location.block];
1847if let Some(terminator) = &bb.terminator
1848// terminator of a loop should be TerminatorKind::FalseUnwind
1849&& let TerminatorKind::FalseUnwind { .. } = terminator.kind
1850 {
1851return Some(location);
1852 }
1853 }
1854None1855 }
18561857/// Access to the SCC constraint graph.
1858 /// This can be used to quickly under-approximate the regions which are equal to each other
1859 /// and their relative orderings.
1860// This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.
1861pub fn constraint_sccs(&self) -> &ConstraintSccs {
1862&self.constraint_sccs
1863 }
18641865/// Returns the representative `RegionVid` for a given SCC.
1866 /// See `RegionTracker` for how a region variable ID is chosen.
1867 ///
1868 /// It is a hacky way to manage checking regions for equality,
1869 /// since we can 'canonicalize' each region to the representative
1870 /// of its SCC and be sure that -- if they have the same repr --
1871 /// they *must* be equal (though not having the same repr does not
1872 /// mean they are unequal).
1873fn scc_representative(&self, scc: ConstraintSccIndex) -> RegionVid {
1874self.scc_annotations[scc].representative.rvid()
1875 }
18761877pub(crate) fn liveness_constraints(&self) -> &LivenessValues {
1878&self.liveness_constraints
1879 }
18801881/// When using `-Zpolonius=next`, records the given live loans for the loan scopes and active
1882 /// loans dataflow computations.
1883pub(crate) fn record_live_loans(&mut self, live_loans: LiveLoans) {
1884self.liveness_constraints.record_live_loans(live_loans);
1885 }
18861887/// Returns whether the `loan_idx` is live at the given `location`: whether its issuing
1888 /// region is contained within the type of a variable that is live at this point.
1889 /// Note: for now, the sets of live loans is only available when using `-Zpolonius=next`.
1890pub(crate) fn is_loan_live_at(&self, loan_idx: BorrowIndex, location: Location) -> bool {
1891let point = self.liveness_constraints.point_from_location(location);
1892self.liveness_constraints.is_loan_live_at(loan_idx, point)
1893 }
1894}
18951896#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for BestBlame<'tcx> {
#[inline]
fn clone(&self) -> BestBlame<'tcx> {
BestBlame {
path: ::core::clone::Clone::clone(&self.path),
idx: ::core::clone::Clone::clone(&self.idx),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for BestBlame<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "BestBlame",
"path", &self.path, "idx", &&self.idx)
}
}Debug)]
1897pub(crate) struct BestBlame<'tcx> {
1898/// See docs on [`RegionInferenceContext::best_blame_constraint`] for what this is.
1899path: Vec<OutlivesConstraint<'tcx>>,
1900/// Index into `path` of the constraint most relevant to report to users.
1901idx: usize,
1902}
19031904impl<'tcx> BestBlame<'tcx> {
1905pub(crate) fn to_obligation_cause(&self) -> ObligationCause<'tcx> {
1906// FIXME - determine what we should do if we encounter multiple
1907 // `ConstraintCategory::Predicate` constraints. Currently, we just pick the first one.
1908let cause_code = self1909 .path
1910 .iter()
1911 .find_map(|constraint| {
1912if let ConstraintCategory::Predicate(predicate_span) = constraint.category {
1913// We currently do not store the `DefId` in the `ConstraintCategory`
1914 // for performances reasons. The error reporting code used by NLL only
1915 // uses the span, so this doesn't cause any problems at the moment.
1916Some(ObligationCauseCode::WhereClause(CRATE_DEF_ID.to_def_id(), predicate_span))
1917 } else {
1918None1919 }
1920 })
1921 .unwrap_or_else(|| ObligationCauseCode::Misc);
19221923ObligationCause::new(self.constraint().span, CRATE_DEF_ID, cause_code.clone())
1924 }
19251926pub(crate) fn constraint(&self) -> &OutlivesConstraint<'tcx> {
1927&self.path[self.idx]
1928 }
19291930pub(crate) fn path(&self) -> &[OutlivesConstraint<'tcx>] {
1931&self.path
1932 }
1933}