1use std::ops::ControlFlow;
23use rustc_infer::infer::TypeOutlivesConstraint;
4use rustc_infer::infer::canonical::{CanonicalQueryInput, CanonicalQueryResponse};
5use rustc_infer::traits::query::OutlivesBound;
6use rustc_infer::traits::query::type_op::ImpliedOutlivesBounds;
7use rustc_middle::traits::ObligationCause;
8use rustc_middle::ty::outlives::{Component, push_outlives_components};
9use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, TypeVisitable, TypeVisitor, Unnormalized};
10use rustc_span::def_id::CRATE_DEF_ID;
11use rustc_span::{DUMMY_SP, Span, sym};
12use smallvec::{SmallVec, smallvec};
1314use crate::infer::InferCtxt;
15use crate::traits::query::NoSolution;
16use crate::traits::query::type_op::QueryTypeOp;
17use crate::traits::{ObligationCtxt, wf};
1819// FIXME(#160491): Remove this once the new implied bounds impl is through FCP.
20impl<'tcx> QueryTypeOp<'tcx> for ImpliedOutlivesBounds<'tcx> {
21type QueryResponse = Vec<OutlivesBound<'tcx>>;
2223fn try_fast_path(
24 _infcx: &InferCtxt<'tcx>,
25 key: &ParamEnvAnd<'tcx, Self>,
26 ) -> Option<Self::QueryResponse> {
27// Don't go into the query for things that can't possibly have lifetimes.
28match key.value.ty.kind() {
29 ty::Tuple(elems) if elems.is_empty() => Some(::alloc::vec::Vec::new()vec![]),
30 ty::Never | ty::Str | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
31Some(::alloc::vec::Vec::new()vec![])
32 }
33_ => None,
34 }
35 }
3637fn perform_query(
38 tcx: TyCtxt<'tcx>,
39 canonicalized: CanonicalQueryInput<'tcx, ParamEnvAnd<'tcx, Self>>,
40 ) -> Result<CanonicalQueryResponse<'tcx, Self::QueryResponse>, NoSolution> {
41tcx.implied_outlives_bounds((canonicalized, false))
42 }
43}
4445pub fn compute_implied_outlives_bounds_inner<'tcx>(
46 ocx: &ObligationCtxt<'_, 'tcx>,
47 param_env: ty::ParamEnv<'tcx>,
48 ty: Ty<'tcx>,
49 normalized_ty: Ty<'tcx>,
50 span: Span,
51) -> Result<Vec<OutlivesBound<'tcx>>, NoSolution> {
52let tcx = ocx.infcx.tcx;
53// Sometimes when we ask what it takes for T: WF, we get back that
54 // U: WF is required; in that case, we push U onto this stack and
55 // process it next. Because the resulting predicates aren't always
56 // guaranteed to be a subset of the original type, so we need to store the
57 // WF args we've computed in a set.
58let mut checked_wf_args = rustc_data_structures::fx::FxHashSet::default();
59let mut wf_args = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ty.into(), normalized_ty.into()]))vec![ty.into(), normalized_ty.into()];
6061let mut outlives_bounds: Vec<OutlivesBound<'tcx>> = ::alloc::vec::Vec::new()vec![];
6263while let Some(arg) = wf_args.pop() {
64if !checked_wf_args.insert(arg) {
65continue;
66 }
6768let arg = ocx.infcx.deeply_resolve_ignoring_regions(arg);
69// From the full set of obligations, just filter down to the region relationships.
70for obligation in
71wf::unnormalized_obligations(ocx.infcx, param_env, arg, DUMMY_SP, CRATE_DEF_ID)
72 .into_flat_iter()
73 {
74let pred = ocx
75 .deeply_normalize(
76&ObligationCause::dummy_with_span(span),
77 param_env,
78 Unnormalized::new_wip(obligation.predicate),
79 )
80 .map_err(|_| NoSolution)?;
81let Some(pred) = pred.kind().no_bound_vars() else {
82continue;
83 };
84match pred {
85// FIXME(generic_const_parameter_types): Make sure that `<'a, 'b, const N: &'a &'b u32>`
86 // is sound if we ever support that
87ty::PredicateKind::Clause(ty::ClauseKind::Trait(..))
88 | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..))
89 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
90 | ty::PredicateKind::Subtype(..)
91 | ty::PredicateKind::Coerce(..)
92 | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..))
93 | ty::PredicateKind::DynCompatible(..)
94 | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
95 | ty::PredicateKind::ConstEquate(..)
96 | ty::PredicateKind::Ambiguous
97 | ty::PredicateKind::NormalizesTo(..)
98 | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(_)) => {}
99100// We need to search through *all* WellFormed predicates
101ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
102 wf_args.push(term);
103 }
104105// We need to register region relationships
106ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(ty::OutlivesClause(
107 r_a,
108 r_b,
109 ))) => outlives_bounds.push(OutlivesBound::RegionSubRegion(r_b, r_a)),
110111 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(ty::OutlivesClause(
112 ty_a,
113 r_b,
114 ))) => {
115let mut components = ::smallvec::SmallVec::new()smallvec![];
116 push_outlives_components(tcx, ty_a, &mut components);
117 outlives_bounds.extend(implied_bounds_from_components(tcx, r_b, components))
118 }
119 ty::PredicateKind::Clause(ty::ClauseKind::CompressedTrait(..)) => ::core::panicking::unreachable_default_msg()unreachable!(),
120 }
121 }
122 }
123124Ok(outlives_bounds)
125}
126127/// If we're at a callsite which should apply the bevy implied bounds hack and
128/// `-Zno-implied-bounds-compat` has not been set, then use the registered outlives
129/// obligations as implied bounds if we detect `bevy_ecs::*::ParamSet` in the arg.
130///
131/// cc #119956
132pub fn consider_implied_bounds_hack_for_ty<'tcx>(
133 ocx: &ObligationCtxt<'_, 'tcx>,
134 ty: Ty<'tcx>,
135 type_outlives_constraints: impl FnOnce() -> Vec<TypeOutlivesConstraint<'tcx>>,
136) -> Vec<OutlivesBound<'tcx>> {
137let tcx = ocx.infcx.tcx;
138if !ocx.infcx.tcx.sess.opts.unstable_opts.no_implied_bounds_compat
139 && ty.visit_with(&mut ContainsBevyParamSet { tcx }).is_break()
140 {
141let mut outlives_bounds = ::alloc::vec::Vec::new()vec![];
142for TypeOutlivesConstraint { sup_type, sub_region, .. } in type_outlives_constraints() {
143let mut components = ::smallvec::SmallVec::new()smallvec![];
144 push_outlives_components(tcx, sup_type, &mut components);
145 outlives_bounds.extend(implied_bounds_from_components(tcx, sub_region, components));
146 }
147outlives_bounds148 } else {
149::alloc::vec::Vec::new()vec![]150 }
151}
152153pub fn query_compute_implied_outlives_bounds<'tcx>(
154 ocx: &ObligationCtxt<'_, 'tcx>,
155 param_env: ty::ParamEnv<'tcx>,
156 ty: Ty<'tcx>,
157 disable_implied_bounds_hack: bool,
158) -> Result<Vec<OutlivesBound<'tcx>>, NoSolution> {
159// When computing implied bounds by looking at types in the signature,
160 // we must be careful to never reveal the hidden types of opaques which
161 // the caller can not. That would be unsound as it may give us implied
162 // bounds which the caller never actually proves.
163 //
164 // FIXME(impl_trait_in_assoc_type): We currently do this incorrectly in
165 // `fn check_opaque_meets_bounds`, see trait-system-refactor-initiative#159.
166 /* if cfg!(debug_assertions) {
167 match ocx.infcx.typing_mode_raw() {
168 TypingMode::Typeck { defining_opaque_types_and_generators: opaque_types }
169 | TypingMode::PostTypeckThroughBorrowck { defining_opaque_types: opaque_types }
170 | TypingMode::PostBorrowck { defined_opaque_types: opaque_types } => {
171 assert!(opaque_types.is_empty())
172 }
173174 TypingMode::Coherence
175 | TypingMode::Reflection
176 | TypingMode::PostAnalysis
177 | TypingMode::Codegen
178 | TypingMode::ErasedNotCoherence(_) => unreachable!(),
179 }
180 } */
181182 // FIXME: This doesn't seem right. All call sites already normalize `ty`.
183 // We have to normalize in the caller as computing implied bounds from unnormalized
184 // types would be unsound. See #100989
185 //
186 // We must normalize the type so we can compute the right outlives components.
187 // for example, if we have some constrained param type like `T: Trait<Out = U>`,
188 // and we know that `&'a T::Out` is WF, then we want to imply `U: 'a`.
189let normalized_ty = ocx
190 .deeply_normalize(&ObligationCause::dummy(), param_env, Unnormalized::new_wip(ty))
191 .map_err(|_| NoSolution)?;
192193let mut outlives_bounds =
194 compute_implied_outlives_bounds_inner(ocx, param_env, ty, normalized_ty, DUMMY_SP)?;
195196if !disable_implied_bounds_hack {
197outlives_bounds.extend(consider_implied_bounds_hack_for_ty(ocx, ty, || {
198ocx.infcx.clone_registered_type_outlives_constraints()
199 }));
200 }
201202Ok(outlives_bounds)
203}
204205struct ContainsBevyParamSet<'tcx> {
206 tcx: TyCtxt<'tcx>,
207}
208209impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsBevyParamSet<'tcx> {
210type Result = ControlFlow<()>;
211212fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
213// We only care to match `ParamSet<T>` or `&ParamSet<T>`.
214match t.kind() {
215 ty::Adt(def, _) => {
216if self.tcx.item_name(def.did()) == sym::ParamSet
217 && self.tcx.crate_name(def.did().krate) == sym::bevy_ecs
218 {
219return ControlFlow::Break(());
220 }
221 }
222 ty::Ref(_, ty, _) => ty.visit_with(self)?,
223_ => {}
224 }
225226 ControlFlow::Continue(())
227 }
228}
229230/// When we have an implied bound that `T: 'a`, we can further break
231/// this down to determine what relationships would have to hold for
232/// `T: 'a` to hold. We get to assume that the caller has validated
233/// those relationships.
234fn implied_bounds_from_components<'tcx>(
235 tcx: TyCtxt<'tcx>,
236 sub_region: ty::Region<'tcx>,
237 sup_components: SmallVec<[Component<TyCtxt<'tcx>>; 4]>,
238) -> Vec<OutlivesBound<'tcx>> {
239sup_components240 .into_iter()
241 .filter_map(|component| {
242match component {
243 Component::Region(r) => Some(OutlivesBound::RegionSubRegion(sub_region, r)),
244 Component::Param(p) => Some(OutlivesBound::RegionSubParam(sub_region, p)),
245 Component::Alias(is_rigid, p) => {
246// We expect them to be already deeply normalized.
247if true {
{
match (&is_rigid, &ty::IsRigid::yes_if_next_solver(tcx)) {
(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!(is_rigid, ty::IsRigid::yes_if_next_solver(tcx));
248Some(OutlivesBound::RegionSubAlias(sub_region, p))
249 }
250 Component::Placeholder(_p) => {
251// FIXME(non_lifetime_binders): Placeholders don't currently
252 // imply anything for outlives, though they could easily.
253None254 }
255 Component::EscapingAlias(_) =>
256// If the projection has escaping regions, don't
257 // try to infer any implied bounds even for its
258 // free components. This is conservative, because
259 // the caller will still have to prove that those
260 // free components outlive `sub_region`. But the
261 // idea is that the WAY that the caller proves
262 // that may change in the future and we want to
263 // give ourselves room to get smarter here.
264{
265None266 }
267 Component::UnresolvedInferenceVariable(..) => None,
268 }
269 })
270 .collect()
271}