]>
Commit | Line | Data |
---|---|---|
9fa01778 | 1 | use crate::infer::InferCtxt; |
ba9703b0 XL |
2 | use crate::opaque_types::required_region_bounds; |
3 | use crate::traits; | |
136023e0 | 4 | use rustc_data_structures::sync::Lrc; |
dfeec247 XL |
5 | use rustc_hir as hir; |
6 | use rustc_hir::def_id::DefId; | |
3dfed10e | 7 | use rustc_hir::lang_items::LangItem; |
f035d41b | 8 | use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef}; |
ba9703b0 | 9 | use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness}; |
dfeec247 | 10 | use rustc_span::Span; |
e9174d1e | 11 | |
1b1a35ee | 12 | use std::iter; |
f035d41b XL |
13 | /// Returns the set of obligations needed to make `arg` well-formed. |
14 | /// If `arg` contains unresolved inference variables, this may include | |
15 | /// further WF obligations. However, if `arg` IS an unresolved | |
e9174d1e SL |
16 | /// inference variable, returns `None`, because we are not able to |
17 | /// make any progress at all. This is to prevent "livelock" where we | |
18 | /// say "$0 is WF if $0 is WF". | |
dc9dc135 XL |
19 | pub fn obligations<'a, 'tcx>( |
20 | infcx: &InferCtxt<'a, 'tcx>, | |
21 | param_env: ty::ParamEnv<'tcx>, | |
22 | body_id: hir::HirId, | |
29967ef6 | 23 | recursion_depth: usize, |
f035d41b | 24 | arg: GenericArg<'tcx>, |
dc9dc135 XL |
25 | span: Span, |
26 | ) -> Option<Vec<traits::PredicateObligation<'tcx>>> { | |
f9f354fc | 27 | // Handle the "livelock" case (see comment above) by bailing out if necessary. |
f035d41b XL |
28 | let arg = match arg.unpack() { |
29 | GenericArgKind::Type(ty) => { | |
1b1a35ee | 30 | match ty.kind() { |
f035d41b XL |
31 | ty::Infer(ty::TyVar(_)) => { |
32 | let resolved_ty = infcx.shallow_resolve(ty); | |
33 | if resolved_ty == ty { | |
34 | // No progress, bail out to prevent "livelock". | |
35 | return None; | |
36 | } | |
37 | ||
38 | resolved_ty | |
39 | } | |
40 | _ => ty, | |
f9f354fc | 41 | } |
f035d41b XL |
42 | .into() |
43 | } | |
44 | GenericArgKind::Const(ct) => { | |
45 | match ct.val { | |
46 | ty::ConstKind::Infer(infer) => { | |
47 | let resolved = infcx.shallow_resolve(infer); | |
48 | if resolved == infer { | |
49 | // No progress. | |
50 | return None; | |
51 | } | |
f9f354fc | 52 | |
f035d41b XL |
53 | infcx.tcx.mk_const(ty::Const { val: ty::ConstKind::Infer(resolved), ty: ct.ty }) |
54 | } | |
55 | _ => ct, | |
56 | } | |
57 | .into() | |
f9f354fc | 58 | } |
f035d41b XL |
59 | // There is nothing we have to do for lifetimes. |
60 | GenericArgKind::Lifetime(..) => return Some(Vec::new()), | |
f9f354fc XL |
61 | }; |
62 | ||
29967ef6 XL |
63 | let mut wf = |
64 | WfPredicates { infcx, param_env, body_id, span, out: vec![], recursion_depth, item: None }; | |
f035d41b XL |
65 | wf.compute(arg); |
66 | debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out); | |
f9f354fc XL |
67 | |
68 | let result = wf.normalize(); | |
f035d41b | 69 | debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", arg, body_id, result); |
f9f354fc | 70 | Some(result) |
e9174d1e SL |
71 | } |
72 | ||
73 | /// Returns the obligations that make this trait reference | |
74 | /// well-formed. For example, if there is a trait `Set` defined like | |
75 | /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF | |
76 | /// if `Bar: Eq`. | |
dc9dc135 XL |
77 | pub fn trait_obligations<'a, 'tcx>( |
78 | infcx: &InferCtxt<'a, 'tcx>, | |
79 | param_env: ty::ParamEnv<'tcx>, | |
80 | body_id: hir::HirId, | |
81 | trait_ref: &ty::TraitRef<'tcx>, | |
82 | span: Span, | |
dfeec247 | 83 | item: Option<&'tcx hir::Item<'tcx>>, |
dc9dc135 | 84 | ) -> Vec<traits::PredicateObligation<'tcx>> { |
29967ef6 XL |
85 | let mut wf = |
86 | WfPredicates { infcx, param_env, body_id, span, out: vec![], recursion_depth: 0, item }; | |
3b2f2976 | 87 | wf.compute_trait_ref(trait_ref, Elaborate::All); |
136023e0 | 88 | debug!(obligations = ?wf.out); |
e9174d1e SL |
89 | wf.normalize() |
90 | } | |
91 | ||
dc9dc135 XL |
92 | pub fn predicate_obligations<'a, 'tcx>( |
93 | infcx: &InferCtxt<'a, 'tcx>, | |
94 | param_env: ty::ParamEnv<'tcx>, | |
95 | body_id: hir::HirId, | |
f9f354fc | 96 | predicate: ty::Predicate<'tcx>, |
dc9dc135 XL |
97 | span: Span, |
98 | ) -> Vec<traits::PredicateObligation<'tcx>> { | |
29967ef6 XL |
99 | let mut wf = WfPredicates { |
100 | infcx, | |
101 | param_env, | |
102 | body_id, | |
103 | span, | |
104 | out: vec![], | |
105 | recursion_depth: 0, | |
106 | item: None, | |
107 | }; | |
e9174d1e | 108 | |
3dfed10e | 109 | // It's ok to skip the binder here because wf code is prepared for it |
5869c6ff XL |
110 | match predicate.kind().skip_binder() { |
111 | ty::PredicateKind::Trait(t, _) => { | |
3dfed10e | 112 | wf.compute_trait_ref(&t.trait_ref, Elaborate::None); |
e9174d1e | 113 | } |
5869c6ff XL |
114 | ty::PredicateKind::RegionOutlives(..) => {} |
115 | ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => { | |
3dfed10e | 116 | wf.compute(ty.into()); |
e9174d1e | 117 | } |
5869c6ff | 118 | ty::PredicateKind::Projection(t) => { |
e9174d1e | 119 | wf.compute_projection(t.projection_ty); |
f035d41b | 120 | wf.compute(t.ty.into()); |
e9174d1e | 121 | } |
5869c6ff | 122 | ty::PredicateKind::WellFormed(arg) => { |
f035d41b | 123 | wf.compute(arg); |
e9174d1e | 124 | } |
5869c6ff XL |
125 | ty::PredicateKind::ObjectSafe(_) => {} |
126 | ty::PredicateKind::ClosureKind(..) => {} | |
127 | ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => { | |
3dfed10e XL |
128 | wf.compute(a.into()); |
129 | wf.compute(b.into()); | |
cc61c64b | 130 | } |
5869c6ff | 131 | ty::PredicateKind::ConstEvaluatable(def, substs) => { |
3dfed10e | 132 | let obligations = wf.nominal_obligations(def.did, substs); |
ea8adc8c XL |
133 | wf.out.extend(obligations); |
134 | ||
f035d41b XL |
135 | for arg in substs.iter() { |
136 | wf.compute(arg); | |
ea8adc8c XL |
137 | } |
138 | } | |
5869c6ff | 139 | ty::PredicateKind::ConstEquate(c1, c2) => { |
f035d41b XL |
140 | wf.compute(c1.into()); |
141 | wf.compute(c2.into()); | |
f9f354fc | 142 | } |
5869c6ff | 143 | ty::PredicateKind::TypeWellFormedFromEnv(..) => { |
1b1a35ee XL |
144 | bug!("TypeWellFormedFromEnv is only used for Chalk") |
145 | } | |
e9174d1e SL |
146 | } |
147 | ||
148 | wf.normalize() | |
149 | } | |
150 | ||
dc9dc135 XL |
151 | struct WfPredicates<'a, 'tcx> { |
152 | infcx: &'a InferCtxt<'a, 'tcx>, | |
7cac9316 | 153 | param_env: ty::ParamEnv<'tcx>, |
9fa01778 | 154 | body_id: hir::HirId, |
e9174d1e SL |
155 | span: Span, |
156 | out: Vec<traits::PredicateObligation<'tcx>>, | |
29967ef6 | 157 | recursion_depth: usize, |
dfeec247 | 158 | item: Option<&'tcx hir::Item<'tcx>>, |
e9174d1e SL |
159 | } |
160 | ||
3b2f2976 XL |
161 | /// Controls whether we "elaborate" supertraits and so forth on the WF |
162 | /// predicates. This is a kind of hack to address #43784. The | |
163 | /// underlying problem in that issue was a trait structure like: | |
164 | /// | |
165 | /// ``` | |
166 | /// trait Foo: Copy { } | |
167 | /// trait Bar: Foo { } | |
168 | /// impl<T: Bar> Foo for T { } | |
169 | /// impl<T> Bar for T { } | |
170 | /// ``` | |
171 | /// | |
172 | /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but | |
173 | /// we decide that this is true because `T: Bar` is in the | |
174 | /// where-clauses (and we can elaborate that to include `T: | |
175 | /// Copy`). This wouldn't be a problem, except that when we check the | |
176 | /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo` | |
177 | /// impl. And so nowhere did we check that `T: Copy` holds! | |
178 | /// | |
179 | /// To resolve this, we elaborate the WF requirements that must be | |
180 | /// proven when checking impls. This means that (e.g.) the `impl Bar | |
181 | /// for T` will be forced to prove not only that `T: Foo` but also `T: | |
182 | /// Copy` (which it won't be able to do, because there is no `Copy` | |
183 | /// impl for `T`). | |
184 | #[derive(Debug, PartialEq, Eq, Copy, Clone)] | |
185 | enum Elaborate { | |
186 | All, | |
187 | None, | |
188 | } | |
189 | ||
ba9703b0 XL |
190 | fn extend_cause_with_original_assoc_item_obligation<'tcx>( |
191 | tcx: TyCtxt<'tcx>, | |
192 | trait_ref: &ty::TraitRef<'tcx>, | |
193 | item: Option<&hir::Item<'tcx>>, | |
194 | cause: &mut traits::ObligationCause<'tcx>, | |
3dfed10e | 195 | pred: &ty::Predicate<'tcx>, |
ba9703b0 XL |
196 | mut trait_assoc_items: impl Iterator<Item = &'tcx ty::AssocItem>, |
197 | ) { | |
198 | debug!( | |
199 | "extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}", | |
200 | trait_ref, item, cause, pred | |
201 | ); | |
202 | let items = match item { | |
5869c6ff | 203 | Some(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) => impl_.items, |
ba9703b0 XL |
204 | _ => return, |
205 | }; | |
206 | let fix_span = | |
207 | |impl_item_ref: &hir::ImplItemRef<'_>| match tcx.hir().impl_item(impl_item_ref.id).kind { | |
208 | hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.span, | |
209 | _ => impl_item_ref.span, | |
210 | }; | |
3dfed10e XL |
211 | |
212 | // It is fine to skip the binder as we don't care about regions here. | |
5869c6ff XL |
213 | match pred.kind().skip_binder() { |
214 | ty::PredicateKind::Projection(proj) => { | |
f9f354fc XL |
215 | // The obligation comes not from the current `impl` nor the `trait` being implemented, |
216 | // but rather from a "second order" obligation, where an associated type has a | |
217 | // projection coming from another associated type. See | |
218 | // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs` and | |
219 | // `traits-assoc-type-in-supertrait-bad.rs`. | |
1b1a35ee | 220 | if let ty::Projection(projection_ty) = proj.ty.kind() { |
f9f354fc XL |
221 | let trait_assoc_item = tcx.associated_item(projection_ty.item_def_id); |
222 | if let Some(impl_item_span) = | |
223 | items.iter().find(|item| item.ident == trait_assoc_item.ident).map(fix_span) | |
224 | { | |
f035d41b | 225 | cause.make_mut().span = impl_item_span; |
ba9703b0 XL |
226 | } |
227 | } | |
228 | } | |
5869c6ff | 229 | ty::PredicateKind::Trait(pred, _) => { |
ba9703b0 XL |
230 | // An associated item obligation born out of the `trait` failed to be met. An example |
231 | // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`. | |
232 | debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred); | |
1b1a35ee | 233 | if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = *pred.self_ty().kind() { |
ba9703b0 | 234 | if let Some(impl_item_span) = trait_assoc_items |
3dfed10e | 235 | .find(|i| i.def_id == item_def_id) |
ba9703b0 XL |
236 | .and_then(|trait_assoc_item| { |
237 | items.iter().find(|i| i.ident == trait_assoc_item.ident).map(fix_span) | |
238 | }) | |
239 | { | |
f035d41b | 240 | cause.make_mut().span = impl_item_span; |
ba9703b0 XL |
241 | } |
242 | } | |
243 | } | |
244 | _ => {} | |
245 | } | |
246 | } | |
247 | ||
dc9dc135 | 248 | impl<'a, 'tcx> WfPredicates<'a, 'tcx> { |
f9f354fc XL |
249 | fn tcx(&self) -> TyCtxt<'tcx> { |
250 | self.infcx.tcx | |
251 | } | |
252 | ||
f035d41b | 253 | fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> { |
9cc50fc6 | 254 | traits::ObligationCause::new(self.span, self.body_id, code) |
e9174d1e SL |
255 | } |
256 | ||
29967ef6 | 257 | fn normalize(mut self) -> Vec<traits::PredicateObligation<'tcx>> { |
e9174d1e SL |
258 | let cause = self.cause(traits::MiscObligation); |
259 | let infcx = &mut self.infcx; | |
7cac9316 | 260 | let param_env = self.param_env; |
74b04a01 | 261 | let mut obligations = Vec::with_capacity(self.out.len()); |
29967ef6 XL |
262 | for mut obligation in self.out { |
263 | assert!(!obligation.has_escaping_bound_vars()); | |
74b04a01 | 264 | let mut selcx = traits::SelectionContext::new(infcx); |
29967ef6 XL |
265 | // Don't normalize the whole obligation, the param env is either |
266 | // already normalized, or we're currently normalizing the | |
267 | // param_env. Either way we should only normalize the predicate. | |
268 | let normalized_predicate = traits::project::normalize_with_depth_to( | |
269 | &mut selcx, | |
270 | param_env, | |
271 | cause.clone(), | |
272 | self.recursion_depth, | |
fc512014 | 273 | obligation.predicate, |
29967ef6 XL |
274 | &mut obligations, |
275 | ); | |
276 | obligation.predicate = normalized_predicate; | |
277 | obligations.push(obligation); | |
74b04a01 XL |
278 | } |
279 | obligations | |
e9174d1e SL |
280 | } |
281 | ||
e74abb32 | 282 | /// Pushes the obligations required for `trait_ref` to be WF into `self.out`. |
3b2f2976 | 283 | fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, elaborate: Elaborate) { |
e74abb32 | 284 | let tcx = self.infcx.tcx; |
e9174d1e | 285 | let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs); |
e9174d1e | 286 | |
ba9703b0 | 287 | debug!("compute_trait_ref obligations {:?}", obligations); |
e9174d1e | 288 | let cause = self.cause(traits::MiscObligation); |
7cac9316 | 289 | let param_env = self.param_env; |
29967ef6 | 290 | let depth = self.recursion_depth; |
3b2f2976 | 291 | |
ba9703b0 | 292 | let item = self.item; |
dfeec247 | 293 | |
ba9703b0 XL |
294 | let extend = |obligation: traits::PredicateObligation<'tcx>| { |
295 | let mut cause = cause.clone(); | |
296 | if let Some(parent_trait_ref) = obligation.predicate.to_opt_poly_trait_ref() { | |
297 | let derived_cause = traits::DerivedObligationCause { | |
fc512014 | 298 | parent_trait_ref: parent_trait_ref.value, |
136023e0 | 299 | parent_code: Lrc::new(obligation.cause.code.clone()), |
ba9703b0 | 300 | }; |
f035d41b XL |
301 | cause.make_mut().code = |
302 | traits::ObligationCauseCode::DerivedObligation(derived_cause); | |
ba9703b0 XL |
303 | } |
304 | extend_cause_with_original_assoc_item_obligation( | |
305 | tcx, | |
306 | trait_ref, | |
307 | item, | |
308 | &mut cause, | |
309 | &obligation.predicate, | |
310 | tcx.associated_items(trait_ref.def_id).in_definition_order(), | |
311 | ); | |
29967ef6 | 312 | traits::Obligation::with_depth(cause, depth, param_env, obligation.predicate) |
ba9703b0 | 313 | }; |
e74abb32 | 314 | |
3b2f2976 | 315 | if let Elaborate::All = elaborate { |
ba9703b0 XL |
316 | let implied_obligations = traits::util::elaborate_obligations(tcx, obligations); |
317 | let implied_obligations = implied_obligations.map(extend); | |
3b2f2976 | 318 | self.out.extend(implied_obligations); |
ba9703b0 XL |
319 | } else { |
320 | self.out.extend(obligations); | |
3b2f2976 XL |
321 | } |
322 | ||
f9f354fc | 323 | let tcx = self.tcx(); |
f035d41b XL |
324 | self.out.extend( |
325 | trait_ref | |
326 | .substs | |
327 | .iter() | |
3dfed10e XL |
328 | .enumerate() |
329 | .filter(|(_, arg)| { | |
f035d41b XL |
330 | matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..)) |
331 | }) | |
3dfed10e XL |
332 | .filter(|(_, arg)| !arg.has_escaping_bound_vars()) |
333 | .map(|(i, arg)| { | |
334 | let mut new_cause = cause.clone(); | |
335 | // The first subst is the self ty - use the correct span for it. | |
336 | if i == 0 { | |
5869c6ff XL |
337 | if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) = |
338 | item.map(|i| &i.kind) | |
339 | { | |
3dfed10e XL |
340 | new_cause.make_mut().span = self_ty.span; |
341 | } | |
342 | } | |
29967ef6 | 343 | traits::Obligation::with_depth( |
3dfed10e | 344 | new_cause, |
29967ef6 | 345 | depth, |
f035d41b | 346 | param_env, |
5869c6ff | 347 | ty::PredicateKind::WellFormed(arg).to_predicate(tcx), |
f035d41b XL |
348 | ) |
349 | }), | |
350 | ); | |
e9174d1e SL |
351 | } |
352 | ||
353 | /// Pushes the obligations required for `trait_ref::Item` to be WF | |
354 | /// into `self.out`. | |
355 | fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) { | |
29967ef6 XL |
356 | // A projection is well-formed if |
357 | // | |
358 | // (a) its predicates hold (*) | |
359 | // (b) its substs are wf | |
360 | // | |
361 | // (*) The predicates of an associated type include the predicates of | |
362 | // the trait that it's contained in. For example, given | |
363 | // | |
364 | // trait A<T>: Clone { | |
365 | // type X where T: Copy; | |
366 | // } | |
367 | // | |
368 | // The predicates of `<() as A<i32>>::X` are: | |
369 | // [ | |
370 | // `(): Sized` | |
371 | // `(): Clone` | |
372 | // `(): A<i32>` | |
373 | // `i32: Sized` | |
374 | // `i32: Clone` | |
375 | // `i32: Copy` | |
376 | // ] | |
377 | let obligations = self.nominal_obligations(data.item_def_id, data.substs); | |
378 | self.out.extend(obligations); | |
379 | ||
380 | let tcx = self.tcx(); | |
381 | let cause = self.cause(traits::MiscObligation); | |
382 | let param_env = self.param_env; | |
383 | let depth = self.recursion_depth; | |
384 | ||
385 | self.out.extend( | |
386 | data.substs | |
387 | .iter() | |
388 | .filter(|arg| { | |
389 | matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..)) | |
390 | }) | |
391 | .filter(|arg| !arg.has_escaping_bound_vars()) | |
392 | .map(|arg| { | |
393 | traits::Obligation::with_depth( | |
394 | cause.clone(), | |
395 | depth, | |
396 | param_env, | |
5869c6ff | 397 | ty::PredicateKind::WellFormed(arg).to_predicate(tcx), |
29967ef6 XL |
398 | ) |
399 | }), | |
400 | ); | |
e9174d1e SL |
401 | } |
402 | ||
9e0c209e | 403 | fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) { |
a1dfa0c6 | 404 | if !subty.has_escaping_bound_vars() { |
a7813a04 | 405 | let cause = self.cause(cause); |
476ff2be | 406 | let trait_ref = ty::TraitRef { |
3dfed10e | 407 | def_id: self.infcx.tcx.require_lang_item(LangItem::Sized, None), |
476ff2be SL |
408 | substs: self.infcx.tcx.mk_substs_trait(subty, &[]), |
409 | }; | |
29967ef6 | 410 | self.out.push(traits::Obligation::with_depth( |
dfeec247 | 411 | cause, |
29967ef6 | 412 | self.recursion_depth, |
dfeec247 | 413 | self.param_env, |
f9f354fc | 414 | trait_ref.without_const().to_predicate(self.infcx.tcx), |
dfeec247 | 415 | )); |
a7813a04 XL |
416 | } |
417 | } | |
418 | ||
f9f354fc | 419 | /// Pushes all the predicates needed to validate that `ty` is WF into `out`. |
f035d41b XL |
420 | fn compute(&mut self, arg: GenericArg<'tcx>) { |
421 | let mut walker = arg.walk(); | |
7cac9316 | 422 | let param_env = self.param_env; |
29967ef6 | 423 | let depth = self.recursion_depth; |
ba9703b0 XL |
424 | while let Some(arg) = walker.next() { |
425 | let ty = match arg.unpack() { | |
426 | GenericArgKind::Type(ty) => ty, | |
427 | ||
428 | // No WF constraints for lifetimes being present, any outlives | |
429 | // obligations are handled by the parent (e.g. `ty::Ref`). | |
430 | GenericArgKind::Lifetime(_) => continue, | |
431 | ||
f035d41b XL |
432 | GenericArgKind::Const(constant) => { |
433 | match constant.val { | |
cdc7bbd5 | 434 | ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) => { |
f035d41b XL |
435 | assert!(promoted.is_none()); |
436 | ||
3dfed10e | 437 | let obligations = self.nominal_obligations(def.did, substs); |
f035d41b XL |
438 | self.out.extend(obligations); |
439 | ||
5869c6ff | 440 | let predicate = ty::PredicateKind::ConstEvaluatable(def, substs) |
f035d41b XL |
441 | .to_predicate(self.tcx()); |
442 | let cause = self.cause(traits::MiscObligation); | |
29967ef6 | 443 | self.out.push(traits::Obligation::with_depth( |
f035d41b | 444 | cause, |
29967ef6 | 445 | self.recursion_depth, |
f035d41b XL |
446 | self.param_env, |
447 | predicate, | |
448 | )); | |
449 | } | |
450 | ty::ConstKind::Infer(infer) => { | |
451 | let resolved = self.infcx.shallow_resolve(infer); | |
452 | // the `InferConst` changed, meaning that we made progress. | |
453 | if resolved != infer { | |
454 | let cause = self.cause(traits::MiscObligation); | |
455 | ||
456 | let resolved_constant = self.infcx.tcx.mk_const(ty::Const { | |
457 | val: ty::ConstKind::Infer(resolved), | |
458 | ..*constant | |
459 | }); | |
29967ef6 | 460 | self.out.push(traits::Obligation::with_depth( |
f035d41b | 461 | cause, |
29967ef6 | 462 | self.recursion_depth, |
f035d41b | 463 | self.param_env, |
5869c6ff | 464 | ty::PredicateKind::WellFormed(resolved_constant.into()) |
f035d41b XL |
465 | .to_predicate(self.tcx()), |
466 | )); | |
467 | } | |
468 | } | |
469 | ty::ConstKind::Error(_) | |
470 | | ty::ConstKind::Param(_) | |
471 | | ty::ConstKind::Bound(..) | |
472 | | ty::ConstKind::Placeholder(..) => { | |
473 | // These variants are trivially WF, so nothing to do here. | |
474 | } | |
475 | ty::ConstKind::Value(..) => { | |
476 | // FIXME: Enforce that values are structurally-matchable. | |
477 | } | |
478 | } | |
479 | continue; | |
480 | } | |
ba9703b0 XL |
481 | }; |
482 | ||
1b1a35ee | 483 | match *ty.kind() { |
dfeec247 XL |
484 | ty::Bool |
485 | | ty::Char | |
486 | | ty::Int(..) | |
487 | | ty::Uint(..) | |
488 | | ty::Float(..) | |
f035d41b | 489 | | ty::Error(_) |
dfeec247 XL |
490 | | ty::Str |
491 | | ty::GeneratorWitness(..) | |
492 | | ty::Never | |
493 | | ty::Param(_) | |
494 | | ty::Bound(..) | |
495 | | ty::Placeholder(..) | |
496 | | ty::Foreign(..) => { | |
e9174d1e SL |
497 | // WfScalar, WfParameter, etc |
498 | } | |
499 | ||
f9f354fc XL |
500 | // Can only infer to `ty::Int(_) | ty::Uint(_)`. |
501 | ty::Infer(ty::IntVar(_)) => {} | |
502 | ||
503 | // Can only infer to `ty::Float(_)`. | |
504 | ty::Infer(ty::FloatVar(_)) => {} | |
505 | ||
b7449926 | 506 | ty::Slice(subty) => { |
ea8adc8c XL |
507 | self.require_sized(subty, traits::SliceOrArrayElem); |
508 | } | |
509 | ||
f035d41b | 510 | ty::Array(subty, _) => { |
9e0c209e | 511 | self.require_sized(subty, traits::SliceOrArrayElem); |
f035d41b | 512 | // Note that we handle the len is implicitly checked while walking `arg`. |
a7813a04 XL |
513 | } |
514 | ||
b7449926 | 515 | ty::Tuple(ref tys) => { |
a7813a04 XL |
516 | if let Some((_last, rest)) = tys.split_last() { |
517 | for elem in rest { | |
48663c56 | 518 | self.require_sized(elem.expect_ty(), traits::TupleElem); |
e9174d1e | 519 | } |
9cc50fc6 | 520 | } |
e9174d1e SL |
521 | } |
522 | ||
b7449926 | 523 | ty::RawPtr(_) => { |
f035d41b | 524 | // Simple cases that are WF if their type args are WF. |
e9174d1e SL |
525 | } |
526 | ||
b7449926 | 527 | ty::Projection(data) => { |
f035d41b | 528 | walker.skip_current_subtree(); // Subtree handled by compute_projection. |
e9174d1e SL |
529 | self.compute_projection(data); |
530 | } | |
531 | ||
b7449926 | 532 | ty::Adt(def, substs) => { |
e9174d1e SL |
533 | // WfNominalType |
534 | let obligations = self.nominal_obligations(def.did, substs); | |
535 | self.out.extend(obligations); | |
536 | } | |
537 | ||
0731742a XL |
538 | ty::FnDef(did, substs) => { |
539 | let obligations = self.nominal_obligations(did, substs); | |
540 | self.out.extend(obligations); | |
541 | } | |
542 | ||
b7449926 | 543 | ty::Ref(r, rty, _) => { |
e9174d1e | 544 | // WfReference |
a1dfa0c6 | 545 | if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() { |
e9174d1e | 546 | let cause = self.cause(traits::ReferenceOutlivesReferent(ty)); |
29967ef6 | 547 | self.out.push(traits::Obligation::with_depth( |
dfeec247 | 548 | cause, |
29967ef6 | 549 | depth, |
dfeec247 | 550 | param_env, |
5869c6ff | 551 | ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(rty, r)) |
3dfed10e | 552 | .to_predicate(self.tcx()), |
dfeec247 | 553 | )); |
e9174d1e SL |
554 | } |
555 | } | |
556 | ||
b7449926 | 557 | ty::Generator(..) => { |
ff7c6d11 XL |
558 | // Walk ALL the types in the generator: this will |
559 | // include the upvar types as well as the yield | |
560 | // type. Note that this is mildly distinct from | |
561 | // the closure case, where we have to be careful | |
562 | // about the signature of the closure. We don't | |
563 | // have the problem of implied bounds here since | |
564 | // generators don't take arguments. | |
565 | } | |
566 | ||
ba9703b0 | 567 | ty::Closure(_, substs) => { |
ff7c6d11 XL |
568 | // Only check the upvar types for WF, not the rest |
569 | // of the types within. This is needed because we | |
570 | // capture the signature and it may not be WF | |
571 | // without the implied bounds. Consider a closure | |
572 | // like `|x: &'a T|` -- it may be that `T: 'a` is | |
573 | // not known to hold in the creator's context (and | |
574 | // indeed the closure may not be invoked by its | |
575 | // creator, but rather turned to someone who *can* | |
576 | // verify that). | |
577 | // | |
578 | // The special treatment of closures here really | |
579 | // ought not to be necessary either; the problem | |
580 | // is related to #25860 -- there is no way for us | |
581 | // to express a fn type complete with the implied | |
582 | // bounds that it is assuming. I think in reality | |
583 | // the WF rules around fn are a bit messed up, and | |
584 | // that is the rot problem: `fn(&'a T)` should | |
585 | // probably always be WF, because it should be | |
586 | // shorthand for something like `where(T: 'a) { | |
587 | // fn(&'a T) }`, as discussed in #25860. | |
9cc50fc6 | 588 | // |
ff7c6d11 XL |
589 | // Note that we are also skipping the generic |
590 | // types. This is consistent with the `outlives` | |
591 | // code, but anyway doesn't matter: within the fn | |
592 | // body where they are created, the generics will | |
593 | // always be WF, and outside of that fn body we | |
594 | // are not directly inspecting closure types | |
595 | // anyway, except via auto trait matching (which | |
596 | // only inspects the upvar types). | |
f9f354fc | 597 | walker.skip_current_subtree(); // subtree handled below |
29967ef6 XL |
598 | // FIXME(eddyb) add the type to `walker` instead of recursing. |
599 | self.compute(substs.as_closure().tupled_upvars_ty().into()); | |
e9174d1e SL |
600 | } |
601 | ||
0731742a | 602 | ty::FnPtr(_) => { |
54a0048b | 603 | // let the loop iterate into the argument/return |
9cc50fc6 | 604 | // types appearing in the fn signature |
e9174d1e SL |
605 | } |
606 | ||
b7449926 | 607 | ty::Opaque(did, substs) => { |
5bcae85e SL |
608 | // all of the requirements on type parameters |
609 | // should've been checked by the instantiation | |
610 | // of whatever returned this exact `impl Trait`. | |
8faf50e0 | 611 | |
416331ca | 612 | // for named opaque `impl Trait` types we still need to check them |
dfeec247 | 613 | if ty::is_impl_trait_defn(self.infcx.tcx, did).is_none() { |
8faf50e0 XL |
614 | let obligations = self.nominal_obligations(did, substs); |
615 | self.out.extend(obligations); | |
616 | } | |
5bcae85e SL |
617 | } |
618 | ||
b7449926 | 619 | ty::Dynamic(data, r) => { |
e9174d1e SL |
620 | // WfObject |
621 | // | |
622 | // Here, we defer WF checking due to higher-ranked | |
623 | // regions. This is perhaps not ideal. | |
476ff2be | 624 | self.from_object_ty(ty, data, r); |
e9174d1e SL |
625 | |
626 | // FIXME(#27579) RFC also considers adding trait | |
627 | // obligations that don't refer to Self and | |
628 | // checking those | |
629 | ||
f9f354fc | 630 | let defer_to_coercion = self.tcx().features().object_safe_for_dispatch; |
e74abb32 XL |
631 | |
632 | if !defer_to_coercion { | |
633 | let cause = self.cause(traits::MiscObligation); | |
dfeec247 | 634 | let component_traits = data.auto_traits().chain(data.principal_def_id()); |
f9f354fc | 635 | let tcx = self.tcx(); |
dfeec247 | 636 | self.out.extend(component_traits.map(|did| { |
29967ef6 | 637 | traits::Obligation::with_depth( |
e74abb32 | 638 | cause.clone(), |
29967ef6 | 639 | depth, |
e74abb32 | 640 | param_env, |
5869c6ff | 641 | ty::PredicateKind::ObjectSafe(did).to_predicate(tcx), |
dfeec247 XL |
642 | ) |
643 | })); | |
e74abb32 | 644 | } |
e9174d1e SL |
645 | } |
646 | ||
647 | // Inference variables are the complicated case, since we don't | |
648 | // know what type they are. We do two things: | |
649 | // | |
650 | // 1. Check if they have been resolved, and if so proceed with | |
651 | // THAT type. | |
f9f354fc XL |
652 | // 2. If not, we've at least simplified things (e.g., we went |
653 | // from `Vec<$0>: WF` to `$0: WF`), so we can | |
e9174d1e SL |
654 | // register a pending obligation and keep |
655 | // moving. (Goal is that an "inductive hypothesis" | |
656 | // is satisfied to ensure termination.) | |
f9f354fc XL |
657 | // See also the comment on `fn obligations`, describing "livelock" |
658 | // prevention, which happens before this can be reached. | |
b7449926 | 659 | ty::Infer(_) => { |
e9174d1e | 660 | let ty = self.infcx.shallow_resolve(ty); |
1b1a35ee | 661 | if let ty::Infer(ty::TyVar(_)) = ty.kind() { |
f9f354fc | 662 | // Not yet resolved, but we've made progress. |
e9174d1e | 663 | let cause = self.cause(traits::MiscObligation); |
29967ef6 | 664 | self.out.push(traits::Obligation::with_depth( |
f9f354fc | 665 | cause, |
29967ef6 | 666 | self.recursion_depth, |
f9f354fc | 667 | param_env, |
5869c6ff | 668 | ty::PredicateKind::WellFormed(ty.into()).to_predicate(self.tcx()), |
f9f354fc | 669 | )); |
e9174d1e | 670 | } else { |
f9f354fc XL |
671 | // Yes, resolved, proceed with the result. |
672 | // FIXME(eddyb) add the type to `walker` instead of recursing. | |
f035d41b | 673 | self.compute(ty.into()); |
e9174d1e SL |
674 | } |
675 | } | |
676 | } | |
677 | } | |
e9174d1e SL |
678 | } |
679 | ||
dfeec247 XL |
680 | fn nominal_obligations( |
681 | &mut self, | |
682 | def_id: DefId, | |
683 | substs: SubstsRef<'tcx>, | |
684 | ) -> Vec<traits::PredicateObligation<'tcx>> { | |
1b1a35ee XL |
685 | let predicates = self.infcx.tcx.predicates_of(def_id); |
686 | let mut origins = vec![def_id; predicates.predicates.len()]; | |
687 | let mut head = predicates; | |
688 | while let Some(parent) = head.parent { | |
689 | head = self.infcx.tcx.predicates_of(parent); | |
690 | origins.extend(iter::repeat(parent).take(head.predicates.len())); | |
691 | } | |
692 | ||
693 | let predicates = predicates.instantiate(self.infcx.tcx, substs); | |
694 | debug_assert_eq!(predicates.predicates.len(), origins.len()); | |
695 | ||
cdc7bbd5 | 696 | iter::zip(iter::zip(predicates.predicates, predicates.spans), origins.into_iter().rev()) |
1b1a35ee XL |
697 | .map(|((pred, span), origin_def_id)| { |
698 | let cause = self.cause(traits::BindingObligation(origin_def_id, span)); | |
29967ef6 | 699 | traits::Obligation::with_depth(cause, self.recursion_depth, self.param_env, pred) |
ba9703b0 | 700 | }) |
dfeec247 XL |
701 | .filter(|pred| !pred.has_escaping_bound_vars()) |
702 | .collect() | |
e9174d1e SL |
703 | } |
704 | ||
dfeec247 XL |
705 | fn from_object_ty( |
706 | &mut self, | |
707 | ty: Ty<'tcx>, | |
cdc7bbd5 | 708 | data: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>, |
dfeec247 XL |
709 | region: ty::Region<'tcx>, |
710 | ) { | |
e9174d1e SL |
711 | // Imagine a type like this: |
712 | // | |
713 | // trait Foo { } | |
714 | // trait Bar<'c> : 'c { } | |
715 | // | |
716 | // &'b (Foo+'c+Bar<'d>) | |
717 | // ^ | |
718 | // | |
719 | // In this case, the following relationships must hold: | |
720 | // | |
721 | // 'b <= 'c | |
722 | // 'd <= 'c | |
723 | // | |
724 | // The first conditions is due to the normal region pointer | |
725 | // rules, which say that a reference cannot outlive its | |
726 | // referent. | |
727 | // | |
728 | // The final condition may be a bit surprising. In particular, | |
729 | // you may expect that it would have been `'c <= 'd`, since | |
730 | // usually lifetimes of outer things are conservative | |
731 | // approximations for inner things. However, it works somewhat | |
732 | // differently with trait objects: here the idea is that if the | |
733 | // user specifies a region bound (`'c`, in this case) it is the | |
734 | // "master bound" that *implies* that bounds from other traits are | |
735 | // all met. (Remember that *all bounds* in a type like | |
736 | // `Foo+Bar+Zed` must be met, not just one, hence if we write | |
737 | // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and | |
738 | // 'y.) | |
739 | // | |
740 | // Note: in fact we only permit builtin traits, not `Bar<'d>`, I | |
741 | // am looking forward to the future here. | |
532ac7d7 | 742 | if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() { |
dfeec247 | 743 | let implicit_bounds = object_region_bounds(self.infcx.tcx, data); |
e9174d1e | 744 | |
476ff2be | 745 | let explicit_bound = region; |
e9174d1e | 746 | |
0bf4aa26 | 747 | self.out.reserve(implicit_bounds.len()); |
e9174d1e | 748 | for implicit_bound in implicit_bounds { |
c30ab7b3 | 749 | let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound)); |
dfeec247 XL |
750 | let outlives = |
751 | ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound)); | |
29967ef6 | 752 | self.out.push(traits::Obligation::with_depth( |
dfeec247 | 753 | cause, |
29967ef6 | 754 | self.recursion_depth, |
dfeec247 | 755 | self.param_env, |
f9f354fc | 756 | outlives.to_predicate(self.infcx.tcx), |
dfeec247 | 757 | )); |
e9174d1e SL |
758 | } |
759 | } | |
760 | } | |
761 | } | |
762 | ||
9fa01778 | 763 | /// Given an object type like `SomeTrait + Send`, computes the lifetime |
e9174d1e SL |
764 | /// bounds that must hold on the elided self type. These are derived |
765 | /// from the declarations of `SomeTrait`, `Send`, and friends -- if | |
766 | /// they declare `trait SomeTrait : 'static`, for example, then | |
767 | /// `'static` would appear in the list. The hard work is done by | |
dfeec247 | 768 | /// `infer::required_region_bounds`, see that for more information. |
dc9dc135 XL |
769 | pub fn object_region_bounds<'tcx>( |
770 | tcx: TyCtxt<'tcx>, | |
cdc7bbd5 | 771 | existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>, |
dc9dc135 | 772 | ) -> Vec<ty::Region<'tcx>> { |
e9174d1e SL |
773 | // Since we don't actually *know* the self type for an object, |
774 | // this "open(err)" serves as a kind of dummy standin -- basically | |
0bf4aa26 | 775 | // a placeholder type. |
48663c56 | 776 | let open_ty = tcx.mk_ty_infer(ty::FreshTy(0)); |
e9174d1e | 777 | |
ba9703b0 | 778 | let predicates = existential_predicates.iter().filter_map(|predicate| { |
f035d41b | 779 | if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() { |
ba9703b0 XL |
780 | None |
781 | } else { | |
782 | Some(predicate.with_self_ty(tcx, open_ty)) | |
60c5eb7d | 783 | } |
ba9703b0 | 784 | }); |
60c5eb7d | 785 | |
ba9703b0 | 786 | required_region_bounds(tcx, open_ty, predicates) |
60c5eb7d | 787 | } |