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