rustc_trait_selection/traits/query/type_op/
implied_outlives_bounds.rs1use rustc_infer::infer::canonical::CanonicalQueryInput;
2use rustc_infer::infer::resolve::OpportunisticRegionResolver;
3use rustc_infer::traits::query::OutlivesBound;
4use rustc_infer::traits::query::type_op::ImpliedOutlivesBounds;
5use rustc_middle::infer::canonical::CanonicalQueryResponse;
6use rustc_middle::traits::ObligationCause;
7use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, TypeFolder, TypeVisitableExt};
8use rustc_span::def_id::CRATE_DEF_ID;
9use rustc_span::{DUMMY_SP, Span};
10use rustc_type_ir::outlives::{Component, push_outlives_components};
11use smallvec::{SmallVec, smallvec};
12use tracing::debug;
13
14use crate::traits::query::NoSolution;
15use crate::traits::{ObligationCtxt, wf};
16
17impl<'tcx> super::QueryTypeOp<'tcx> for ImpliedOutlivesBounds<'tcx> {
18 type QueryResponse = Vec<OutlivesBound<'tcx>>;
19
20 fn try_fast_path(
21 _tcx: TyCtxt<'tcx>,
22 key: &ParamEnvAnd<'tcx, Self>,
23 ) -> Option<Self::QueryResponse> {
24 match key.value.ty.kind() {
26 ty::Tuple(elems) if elems.is_empty() => Some(vec![]),
27 ty::Never | ty::Str | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
28 Some(vec![])
29 }
30 _ => None,
31 }
32 }
33
34 fn perform_query(
35 tcx: TyCtxt<'tcx>,
36 canonicalized: CanonicalQueryInput<'tcx, ParamEnvAnd<'tcx, Self>>,
37 ) -> Result<CanonicalQueryResponse<'tcx, Self::QueryResponse>, NoSolution> {
38 if tcx.sess.opts.unstable_opts.no_implied_bounds_compat {
39 tcx.implied_outlives_bounds(canonicalized)
40 } else {
41 tcx.implied_outlives_bounds_compat(canonicalized)
42 }
43 }
44
45 fn perform_locally_with_next_solver(
46 ocx: &ObligationCtxt<'_, 'tcx>,
47 key: ParamEnvAnd<'tcx, Self>,
48 span: Span,
49 ) -> Result<Self::QueryResponse, NoSolution> {
50 if ocx.infcx.tcx.sess.opts.unstable_opts.no_implied_bounds_compat {
51 compute_implied_outlives_bounds_inner(ocx, key.param_env, key.value.ty, span)
52 } else {
53 compute_implied_outlives_bounds_compat_inner(ocx, key.param_env, key.value.ty, span)
54 }
55 }
56}
57
58pub fn compute_implied_outlives_bounds_inner<'tcx>(
59 ocx: &ObligationCtxt<'_, 'tcx>,
60 param_env: ty::ParamEnv<'tcx>,
61 ty: Ty<'tcx>,
62 span: Span,
63) -> Result<Vec<OutlivesBound<'tcx>>, NoSolution> {
64 let normalize_op = |ty| -> Result<_, NoSolution> {
65 let ty = ocx
69 .deeply_normalize(&ObligationCause::dummy_with_span(span), param_env, ty)
70 .map_err(|_| NoSolution)?;
71 if !ocx.select_all_or_error().is_empty() {
72 return Err(NoSolution);
73 }
74 let ty = OpportunisticRegionResolver::new(&ocx.infcx).fold_ty(ty);
75 Ok(ty)
76 };
77
78 let mut checked_wf_args = rustc_data_structures::fx::FxHashSet::default();
84 let mut wf_args = vec![ty.into(), normalize_op(ty)?.into()];
85
86 let mut outlives_bounds: Vec<OutlivesBound<'tcx>> = vec![];
87
88 while let Some(arg) = wf_args.pop() {
89 if !checked_wf_args.insert(arg) {
90 continue;
91 }
92
93 for obligation in
95 wf::unnormalized_obligations(ocx.infcx, param_env, arg, DUMMY_SP, CRATE_DEF_ID)
96 .into_iter()
97 .flatten()
98 {
99 assert!(!obligation.has_escaping_bound_vars());
100 let Some(pred) = obligation.predicate.kind().no_bound_vars() else {
101 continue;
102 };
103 match pred {
104 ty::PredicateKind::Clause(ty::ClauseKind::Trait(..))
107 | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..))
108 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
109 | ty::PredicateKind::Subtype(..)
110 | ty::PredicateKind::Coerce(..)
111 | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..))
112 | ty::PredicateKind::DynCompatible(..)
113 | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
114 | ty::PredicateKind::ConstEquate(..)
115 | ty::PredicateKind::Ambiguous
116 | ty::PredicateKind::NormalizesTo(..)
117 | ty::PredicateKind::AliasRelate(..) => {}
118
119 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
121 wf_args.push(arg);
122 }
123
124 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(
126 ty::OutlivesPredicate(r_a, r_b),
127 )) => outlives_bounds.push(OutlivesBound::RegionSubRegion(r_b, r_a)),
128
129 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(
130 ty_a,
131 r_b,
132 ))) => {
133 let ty_a = normalize_op(ty_a)?;
134 let mut components = smallvec![];
135 push_outlives_components(ocx.infcx.tcx, ty_a, &mut components);
136 outlives_bounds.extend(implied_bounds_from_components(r_b, components))
137 }
138 }
139 }
140 }
141
142 Ok(outlives_bounds)
143}
144
145pub fn compute_implied_outlives_bounds_compat_inner<'tcx>(
146 ocx: &ObligationCtxt<'_, 'tcx>,
147 param_env: ty::ParamEnv<'tcx>,
148 ty: Ty<'tcx>,
149 span: Span,
150) -> Result<Vec<OutlivesBound<'tcx>>, NoSolution> {
151 let tcx = ocx.infcx.tcx;
152
153 let mut checked_wf_args = rustc_data_structures::fx::FxHashSet::default();
159 let mut wf_args = vec![ty.into()];
160
161 let mut outlives_bounds: Vec<ty::OutlivesPredicate<'tcx, ty::GenericArg<'tcx>>> = vec![];
162
163 while let Some(arg) = wf_args.pop() {
164 if !checked_wf_args.insert(arg) {
165 continue;
166 }
167
168 let obligations =
180 wf::obligations(ocx.infcx, param_env, CRATE_DEF_ID, 0, arg, span).unwrap_or_default();
181
182 for obligation in obligations {
183 debug!(?obligation);
184 assert!(!obligation.has_escaping_bound_vars());
185
186 if obligation.predicate.has_non_region_infer() {
196 match obligation.predicate.kind().skip_binder() {
197 ty::PredicateKind::Clause(ty::ClauseKind::Projection(..))
198 | ty::PredicateKind::AliasRelate(..) => {
199 ocx.register_obligation(obligation.clone());
200 }
201 _ => {}
202 }
203 }
204
205 let pred = match obligation.predicate.kind().no_bound_vars() {
206 None => continue,
207 Some(pred) => pred,
208 };
209 match pred {
210 ty::PredicateKind::Clause(ty::ClauseKind::Trait(..))
213 | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..))
214 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
215 | ty::PredicateKind::Subtype(..)
216 | ty::PredicateKind::Coerce(..)
217 | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..))
218 | ty::PredicateKind::DynCompatible(..)
219 | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
220 | ty::PredicateKind::ConstEquate(..)
221 | ty::PredicateKind::Ambiguous
222 | ty::PredicateKind::NormalizesTo(..)
223 | ty::PredicateKind::AliasRelate(..) => {}
224
225 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
227 wf_args.push(arg);
228 }
229
230 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(
232 ty::OutlivesPredicate(r_a, r_b),
233 )) => outlives_bounds.push(ty::OutlivesPredicate(r_a.into(), r_b)),
234
235 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(
236 ty_a,
237 r_b,
238 ))) => outlives_bounds.push(ty::OutlivesPredicate(ty_a.into(), r_b)),
239 }
240 }
241 }
242
243 match ocx.select_all_or_error().as_slice() {
246 [] => (),
247 _ => return Err(NoSolution),
248 }
249
250 let mut implied_bounds = Vec::new();
253 for ty::OutlivesPredicate(a, r_b) in outlives_bounds {
254 match a.unpack() {
255 ty::GenericArgKind::Lifetime(r_a) => {
256 implied_bounds.push(OutlivesBound::RegionSubRegion(r_b, r_a))
257 }
258 ty::GenericArgKind::Type(ty_a) => {
259 let mut ty_a = ocx.infcx.resolve_vars_if_possible(ty_a);
260 if ocx.infcx.next_trait_solver() {
262 ty_a = ocx
263 .deeply_normalize(&ObligationCause::dummy_with_span(span), param_env, ty_a)
264 .map_err(|_| NoSolution)?;
265 }
266 let mut components = smallvec![];
267 push_outlives_components(tcx, ty_a, &mut components);
268 implied_bounds.extend(implied_bounds_from_components(r_b, components))
269 }
270 ty::GenericArgKind::Const(_) => {
271 unreachable!("consts do not participate in outlives bounds")
272 }
273 }
274 }
275
276 Ok(implied_bounds)
277}
278
279fn implied_bounds_from_components<'tcx>(
284 sub_region: ty::Region<'tcx>,
285 sup_components: SmallVec<[Component<TyCtxt<'tcx>>; 4]>,
286) -> Vec<OutlivesBound<'tcx>> {
287 sup_components
288 .into_iter()
289 .filter_map(|component| {
290 match component {
291 Component::Region(r) => Some(OutlivesBound::RegionSubRegion(sub_region, r)),
292 Component::Param(p) => Some(OutlivesBound::RegionSubParam(sub_region, p)),
293 Component::Alias(p) => Some(OutlivesBound::RegionSubAlias(sub_region, p)),
294 Component::Placeholder(_p) => {
295 None
298 }
299 Component::EscapingAlias(_) =>
300 {
309 None
310 }
311 Component::UnresolvedInferenceVariable(..) => None,
312 }
313 })
314 .collect()
315}