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