1use rustc_hir::def::DefKind;
2use rustc_hir::def_id::LocalDefId;
3use rustc_infer::infer::TyCtxtInferExt;
4use rustc_infer::traits::ObligationCause;
5use rustc_infer::traits::query::MirBorrowckImpliedOutlivesBounds;
6use rustc_middle::infer::canonical::{Canonical, QueryResponse};
7use rustc_middle::ty::{
8self, CanonicalVarValues, GenericArg, Ty, TyCtxt, TypeVisitableExt, TypingEnv, fold_regions,
9};
10use rustc_span::DUMMY_SP;
11use rustc_trait_selection::solve::NoSolution;
12use rustc_trait_selection::traits::ObligationCtxt;
13use rustc_trait_selection::traits::implied_outlives_bounds::{
14compute_implied_outlives_bounds_inner, consider_implied_bounds_hack_for_ty,
15};
16use smallvec::SmallVec;
17use tracing::instrument;
1819use crate::universal_regions::DefiningTy;
2021/// Computes the implied bounds for `body_def_id`. This is a separate query
22/// as it must not reveal the hidden type of opaques defined by `body_def_id`
23/// for typeck roots.
24///
25/// However, nested bodies are checked in the scope of their parent. This means
26/// we should actually normalize opaques when computing their implied bounds.
27pub(super) fn mir_borrowck_implied_outlives_bounds<'tcx>(
28 tcx: TyCtxt<'tcx>,
29 body_def_id: LocalDefId,
30) -> Result<
31&'tcx Canonical<'tcx, QueryResponse<'tcx, MirBorrowckImpliedOutlivesBounds<'tcx>>>,
32NoSolution,
33> {
34// If we're in a typeck root we don't want to reveal any opaque types. We need to
35 // make sure the caller actually checks that all our implied bounds actually hold.
36 // This is not the case with the hidden types of opaque types if we're a defining-scope
37 // and the caller is not.
38 //
39 // However, for nested bodies, we always check that they are well-formed in their
40 // parent body, so for these we do want to define opaque types. Not doing so can result
41 // in incorrect errors when normalizing implied bounds.
42let typing_env = if tcx.is_typeck_child(body_def_id.to_def_id()) {
43TypingEnv::post_typeck_through_borrowck(tcx, body_def_id)
44 } else {
45TypingEnv::non_body_analysis(tcx, body_def_id)
46 };
4748let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
49let ocx = ObligationCtxt::new(&infcx);
5051let defining_ty = DefiningTy::new(tcx, body_def_id);
5253let inputs_and_output = defining_ty.inputs_and_output(tcx);
54let inputs_and_output =
55tcx.liberate_late_bound_regions(body_def_id.to_def_id(), inputs_and_output);
56let inputs_and_output = replace_erased_regions_with_placeholders(tcx, inputs_and_output);
5758let mut outlives_bounds = ::alloc::vec::Vec::new()vec![];
59// Need to return the normalized signature used to compute implied bounds back to borrowck
60 // to deal with unconstrained regions due to #136547.
61let mut normalized_inputs_and_output = Vec::with_capacity(inputs_and_output.len());
62for &ty in &inputs_and_output {
63let num_registered_type_outlives_constraints =
64 infcx.num_registered_type_outlives_constraints();
65let normalized_ty = ocx
66 .deeply_normalize(&ObligationCause::dummy(), param_env, ty::Unnormalized::new_wip(ty))
67 .map_err(|_| NoSolution)?;
6869 outlives_bounds.extend(compute_implied_outlives_bounds_inner(
70&ocx,
71 param_env,
72 ty,
73 normalized_ty,
74 DUMMY_SP,
75 )?);
7677 outlives_bounds.extend(consider_implied_bounds_hack_for_ty(&ocx, normalized_ty, || {
78 infcx.registered_type_outlives_constraints_since(
79 num_registered_type_outlives_constraints,
80 )
81 }));
8283 normalized_inputs_and_output.push(normalized_ty);
84 }
8586// Add implied bounds from impl header.
87 //
88 // We don't use `assumed_wf_types` to source the entire set of implied bounds for
89 // a few reasons:
90 // - `DefiningTy` for closure has the `&'env Self` type while `assumed_wf_types` doesn't
91 // - We compute implied bounds from the unnormalized types in the `DefiningTy` but do not
92 // do so for types in impl headers
93 // - We must compute the normalized signature and then compute implied bounds from that
94 // in order to connect any unconstrained region vars created during normalization to
95 // the types of the locals corresponding to the inputs and outputs of the item. #136547
96if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(body_def_id) {
DefKind::AssocFn | DefKind::AssocConst => true,
_ => false,
}matches!(tcx.def_kind(body_def_id), DefKind::AssocFn | DefKind::AssocConst) {
97for &(ty, _) in tcx.assumed_wf_types(tcx.local_parent(body_def_id)) {
98let normalized_ty = ocx
99 .deeply_normalize(
100&ObligationCause::dummy(),
101 param_env,
102 ty::Unnormalized::new_wip(ty),
103 )
104 .map_err(|_| NoSolution)?;
105106// We don't consider the constraints from normalizing the impl header
107 // for the bevy implied bounds hack.
108let num_registered_type_outlives_constraints =
109 infcx.num_registered_type_outlives_constraints();
110 outlives_bounds.extend(compute_implied_outlives_bounds_inner(
111&ocx,
112 param_env,
113 normalized_ty,
114 normalized_ty,
115 DUMMY_SP,
116 )?);
117118 outlives_bounds.extend(consider_implied_bounds_hack_for_ty(
119&ocx,
120 normalized_ty,
121 || {
122 infcx.registered_type_outlives_constraints_since(
123 num_registered_type_outlives_constraints,
124 )
125 },
126 ));
127 }
128 }
129130let var_values = implied_bounds_query_var_values(tcx, &inputs_and_output, |r| match r.kind() {
131 ty::RePlaceholder(_) => true,
132 ty::ReEarlyParam(_)
133 | ty::ReLateParam(_)
134 | ty::ReBound(..)
135 | ty::ReStatic136 | ty::ReError(_) => false,
137 ty::ReVar(..) | ty::ReErased => ::core::panicking::unreachable_default_msg()unreachable!(),
138 });
139let input_values = CanonicalVarValues { var_values: tcx.mk_args(&var_values) };
140141ocx.make_canonicalized_query_response(
142input_values,
143MirBorrowckImpliedOutlivesBounds { outlives_bounds, normalized_inputs_and_output },
144 )
145}
146147/// This computes the `var_values` used by the `mir_borrowck_implied_outlives_bounds` query.
148/// The old solver canonicalization does not replace early and late bound parameters,
149/// so the only `var_values` we need are external regions from the signature of the nested
150/// body as we don't have a shared representation between this query and MIR borrowck.
151///
152/// These are not all external regions of the nested body, only the external regions
153/// which may get accessed by this query. We only need to add things to the `var_values`
154/// which can be referenced by both this query and MIR borrowck. MIR borrowck currently
155/// creates external regions for late-bound regions of parent items as these can be
156/// explicitly mentioned in user types. We do not encounter these in this query, as all
157/// free regions in the signature of nested bodies get replaced with `'erased` at the end
158/// of HIR typeck, so we don't care about them.
159{}
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("implied_bounds_query_var_values",
"rustc_borrowck::implied_bounds", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/implied_bounds.rs"),
::tracing_core::__macro_support::Option::Some(159u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::implied_bounds"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("unnormalized_inputs_and_output")
}> =
::tracing::__macro_support::FieldName::new("unnormalized_inputs_and_output");
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(&unnormalized_inputs_and_output)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
SmallVec<[GenericArg<'tcx>; 8]> = loop {};
return __tracing_attr_fake_return;
}
{
let mut values: SmallVec<[GenericArg<'tcx>; 8]> =
Default::default();
for ty in unnormalized_inputs_and_output {
tcx.for_each_free_region(ty,
|region|
{
if is_external_region(region) {
values.push(region.into());
}
});
}
values
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/implied_bounds.rs:159",
"rustc_borrowck::implied_bounds", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/implied_bounds.rs"),
::tracing_core::__macro_support::Option::Some(159u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::implied_bounds"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
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(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(tcx, is_external_region), ret)]160pub(crate) fn implied_bounds_query_var_values<'tcx>(
161 tcx: TyCtxt<'tcx>,
162 unnormalized_inputs_and_output: &[Ty<'tcx>],
163mut is_external_region: impl FnMut(ty::Region<'tcx>) -> bool,
164) -> SmallVec<[GenericArg<'tcx>; 8]> {
165let mut values: SmallVec<[GenericArg<'tcx>; 8]> = Default::default();
166167for ty in unnormalized_inputs_and_output {
168 tcx.for_each_free_region(ty, |region| {
169if is_external_region(region) {
170 values.push(region.into());
171 }
172 });
173 }
174175 values
176}
177178/// This replaces all external regions in the signature of the current item with
179/// a unique placeholder to collect its implied bounds. This mirrors the way MIR
180/// borrowck replaces all of them with unique NLL vars.
181fn replace_erased_regions_with_placeholders<'tcx>(
182 tcx: TyCtxt<'tcx>,
183 inputs_and_output: &[Ty<'tcx>],
184) -> Vec<Ty<'tcx>> {
185if true {
if !!inputs_and_output.has_placeholders() {
::core::panicking::panic("assertion failed: !inputs_and_output.has_placeholders()")
};
};debug_assert!(!inputs_and_output.has_placeholders());
186let mut next_placeholder = 0;
187inputs_and_output188 .iter()
189 .map(|&ty| {
190fold_regions(tcx, ty, |r, _| match r.kind() {
191 ty::ReErased => {
192let var = ty::BoundVar::from_usize(next_placeholder);
193next_placeholder += 1;
194 ty::Region::new_placeholder(
195tcx,
196 ty::PlaceholderRegion::new(
197 ty::UniverseIndex::ROOT,
198 ty::BoundRegion { var, kind: ty::BoundRegionKind::Anon },
199 ),
200 )
201 }
202 ty::ReEarlyParam(_)
203 | ty::ReLateParam(_)
204 | ty::ReBound(..)
205 | ty::ReStatic206 | ty::ReError(_) => r,
207 ty::ReVar(..) | ty::RePlaceholder(..) => {
208{ ::core::panicking::panic_fmt(format_args!("unexpected region: {0:?}", r)); }panic!("unexpected region: {r:?}")209 }
210 })
211 })
212 .collect()
213}