]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/wf.rs
Rollup merge of #60315 - pietroalbini:fix-tools-version, r=Mark-Simulacrum
[rust.git] / src / librustc / ty / wf.rs
1 use crate::hir;
2 use crate::hir::def_id::DefId;
3 use crate::infer::InferCtxt;
4 use crate::ty::subst::SubstsRef;
5 use crate::traits;
6 use crate::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable};
7 use std::iter::once;
8 use syntax_pos::Span;
9 use crate::middle::lang_items;
10 use crate::mir::interpret::ConstValue;
11
12 /// Returns the set of obligations needed to make `ty` well-formed.
13 /// If `ty` contains unresolved inference variables, this may include
14 /// further WF obligations. However, if `ty` IS an unresolved
15 /// inference variable, returns `None`, because we are not able to
16 /// make any progress at all. This is to prevent "livelock" where we
17 /// say "$0 is WF if $0 is WF".
18 pub fn obligations<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
19                                    param_env: ty::ParamEnv<'tcx>,
20                                    body_id: hir::HirId,
21                                    ty: Ty<'tcx>,
22                                    span: Span)
23                                    -> Option<Vec<traits::PredicateObligation<'tcx>>>
24 {
25     let mut wf = WfPredicates { infcx,
26                                 param_env,
27                                 body_id,
28                                 span,
29                                 out: vec![] };
30     if wf.compute(ty) {
31         debug!("wf::obligations({:?}, body_id={:?}) = {:?}", ty, body_id, wf.out);
32         let result = wf.normalize();
33         debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", ty, body_id, result);
34         Some(result)
35     } else {
36         None // no progress made, return None
37     }
38 }
39
40 /// Returns the obligations that make this trait reference
41 /// well-formed.  For example, if there is a trait `Set` defined like
42 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
43 /// if `Bar: Eq`.
44 pub fn trait_obligations<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
45                                          param_env: ty::ParamEnv<'tcx>,
46                                          body_id: hir::HirId,
47                                          trait_ref: &ty::TraitRef<'tcx>,
48                                          span: Span)
49                                          -> Vec<traits::PredicateObligation<'tcx>>
50 {
51     let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![] };
52     wf.compute_trait_ref(trait_ref, Elaborate::All);
53     wf.normalize()
54 }
55
56 pub fn predicate_obligations<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
57                                              param_env: ty::ParamEnv<'tcx>,
58                                              body_id: hir::HirId,
59                                              predicate: &ty::Predicate<'tcx>,
60                                              span: Span)
61                                              -> Vec<traits::PredicateObligation<'tcx>>
62 {
63     let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![] };
64
65     // (*) ok to skip binders, because wf code is prepared for it
66     match *predicate {
67         ty::Predicate::Trait(ref t) => {
68             wf.compute_trait_ref(&t.skip_binder().trait_ref, Elaborate::None); // (*)
69         }
70         ty::Predicate::RegionOutlives(..) => {
71         }
72         ty::Predicate::TypeOutlives(ref t) => {
73             wf.compute(t.skip_binder().0);
74         }
75         ty::Predicate::Projection(ref t) => {
76             let t = t.skip_binder(); // (*)
77             wf.compute_projection(t.projection_ty);
78             wf.compute(t.ty);
79         }
80         ty::Predicate::WellFormed(t) => {
81             wf.compute(t);
82         }
83         ty::Predicate::ObjectSafe(_) => {
84         }
85         ty::Predicate::ClosureKind(..) => {
86         }
87         ty::Predicate::Subtype(ref data) => {
88             wf.compute(data.skip_binder().a); // (*)
89             wf.compute(data.skip_binder().b); // (*)
90         }
91         ty::Predicate::ConstEvaluatable(def_id, substs) => {
92             let obligations = wf.nominal_obligations(def_id, substs);
93             wf.out.extend(obligations);
94
95             for ty in substs.types() {
96                 wf.compute(ty);
97             }
98         }
99     }
100
101     wf.normalize()
102 }
103
104 struct WfPredicates<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
105     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
106     param_env: ty::ParamEnv<'tcx>,
107     body_id: hir::HirId,
108     span: Span,
109     out: Vec<traits::PredicateObligation<'tcx>>,
110 }
111
112 /// Controls whether we "elaborate" supertraits and so forth on the WF
113 /// predicates. This is a kind of hack to address #43784. The
114 /// underlying problem in that issue was a trait structure like:
115 ///
116 /// ```
117 /// trait Foo: Copy { }
118 /// trait Bar: Foo { }
119 /// impl<T: Bar> Foo for T { }
120 /// impl<T> Bar for T { }
121 /// ```
122 ///
123 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
124 /// we decide that this is true because `T: Bar` is in the
125 /// where-clauses (and we can elaborate that to include `T:
126 /// Copy`). This wouldn't be a problem, except that when we check the
127 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
128 /// impl. And so nowhere did we check that `T: Copy` holds!
129 ///
130 /// To resolve this, we elaborate the WF requirements that must be
131 /// proven when checking impls. This means that (e.g.) the `impl Bar
132 /// for T` will be forced to prove not only that `T: Foo` but also `T:
133 /// Copy` (which it won't be able to do, because there is no `Copy`
134 /// impl for `T`).
135 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
136 enum Elaborate {
137     All,
138     None,
139 }
140
141 impl<'a, 'gcx, 'tcx> WfPredicates<'a, 'gcx, 'tcx> {
142     fn cause(&mut self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
143         traits::ObligationCause::new(self.span, self.body_id, code)
144     }
145
146     fn normalize(&mut self) -> Vec<traits::PredicateObligation<'tcx>> {
147         let cause = self.cause(traits::MiscObligation);
148         let infcx = &mut self.infcx;
149         let param_env = self.param_env;
150         self.out.iter()
151                 .inspect(|pred| assert!(!pred.has_escaping_bound_vars()))
152                 .flat_map(|pred| {
153                     let mut selcx = traits::SelectionContext::new(infcx);
154                     let pred = traits::normalize(&mut selcx, param_env, cause.clone(), pred);
155                     once(pred.value).chain(pred.obligations)
156                 })
157                 .collect()
158     }
159
160     /// Pushes the obligations required for `trait_ref` to be WF into
161     /// `self.out`.
162     fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, elaborate: Elaborate) {
163         let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs);
164
165         let cause = self.cause(traits::MiscObligation);
166         let param_env = self.param_env;
167
168         if let Elaborate::All = elaborate {
169             let predicates = obligations.iter()
170                                         .map(|obligation| obligation.predicate.clone())
171                                         .collect();
172             let implied_obligations = traits::elaborate_predicates(self.infcx.tcx, predicates);
173             let implied_obligations = implied_obligations.map(|pred| {
174                 traits::Obligation::new(cause.clone(), param_env, pred)
175             });
176             self.out.extend(implied_obligations);
177         }
178
179         self.out.extend(obligations);
180
181         self.out.extend(
182             trait_ref.substs.types()
183                             .filter(|ty| !ty.has_escaping_bound_vars())
184                             .map(|ty| traits::Obligation::new(cause.clone(),
185                                                               param_env,
186                                                               ty::Predicate::WellFormed(ty))));
187     }
188
189     /// Pushes the obligations required for `trait_ref::Item` to be WF
190     /// into `self.out`.
191     fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
192         // A projection is well-formed if (a) the trait ref itself is
193         // WF and (b) the trait-ref holds.  (It may also be
194         // normalizable and be WF that way.)
195         let trait_ref = data.trait_ref(self.infcx.tcx);
196         self.compute_trait_ref(&trait_ref, Elaborate::None);
197
198         if !data.has_escaping_bound_vars() {
199             let predicate = trait_ref.to_predicate();
200             let cause = self.cause(traits::ProjectionWf(data));
201             self.out.push(traits::Obligation::new(cause, self.param_env, predicate));
202         }
203     }
204
205     /// Pushes the obligations required for an array length to be WF
206     /// into `self.out`.
207     fn compute_array_len(&mut self, constant: ty::Const<'tcx>) {
208         if let ConstValue::Unevaluated(def_id, substs) = constant.val {
209             let obligations = self.nominal_obligations(def_id, substs);
210             self.out.extend(obligations);
211
212             let predicate = ty::Predicate::ConstEvaluatable(def_id, substs);
213             let cause = self.cause(traits::MiscObligation);
214             self.out.push(traits::Obligation::new(cause,
215                                                   self.param_env,
216                                                   predicate));
217         }
218     }
219
220     fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
221         if !subty.has_escaping_bound_vars() {
222             let cause = self.cause(cause);
223             let trait_ref = ty::TraitRef {
224                 def_id: self.infcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
225                 substs: self.infcx.tcx.mk_substs_trait(subty, &[]),
226             };
227             self.out.push(traits::Obligation::new(cause, self.param_env, trait_ref.to_predicate()));
228         }
229     }
230
231     /// Pushes new obligations into `out`. Returns `true` if it was able
232     /// to generate all the predicates needed to validate that `ty0`
233     /// is WF. Returns false if `ty0` is an unresolved type variable,
234     /// in which case we are not able to simplify at all.
235     fn compute(&mut self, ty0: Ty<'tcx>) -> bool {
236         let mut subtys = ty0.walk();
237         let param_env = self.param_env;
238         while let Some(ty) = subtys.next() {
239             match ty.sty {
240                 ty::Bool |
241                 ty::Char |
242                 ty::Int(..) |
243                 ty::Uint(..) |
244                 ty::Float(..) |
245                 ty::Error |
246                 ty::Str |
247                 ty::GeneratorWitness(..) |
248                 ty::Never |
249                 ty::Param(_) |
250                 ty::Bound(..) |
251                 ty::Placeholder(..) |
252                 ty::Foreign(..) => {
253                     // WfScalar, WfParameter, etc
254                 }
255
256                 ty::Slice(subty) => {
257                     self.require_sized(subty, traits::SliceOrArrayElem);
258                 }
259
260                 ty::Array(subty, len) => {
261                     self.require_sized(subty, traits::SliceOrArrayElem);
262                     self.compute_array_len(*len);
263                 }
264
265                 ty::Tuple(ref tys) => {
266                     if let Some((_last, rest)) = tys.split_last() {
267                         for elem in rest {
268                             self.require_sized(elem.expect_ty(), traits::TupleElem);
269                         }
270                     }
271                 }
272
273                 ty::RawPtr(_) => {
274                     // simple cases that are WF if their type args are WF
275                 }
276
277                 ty::Projection(data) => {
278                     subtys.skip_current_subtree(); // subtree handled by compute_projection
279                     self.compute_projection(data);
280                 }
281
282                 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
283
284                 ty::Adt(def, substs) => {
285                     // WfNominalType
286                     let obligations = self.nominal_obligations(def.did, substs);
287                     self.out.extend(obligations);
288                 }
289
290                 ty::FnDef(did, substs) => {
291                     let obligations = self.nominal_obligations(did, substs);
292                     self.out.extend(obligations);
293                 }
294
295                 ty::Ref(r, rty, _) => {
296                     // WfReference
297                     if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
298                         let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
299                         self.out.push(
300                             traits::Obligation::new(
301                                 cause,
302                                 param_env,
303                                 ty::Predicate::TypeOutlives(
304                                     ty::Binder::dummy(
305                                         ty::OutlivesPredicate(rty, r)))));
306                     }
307                 }
308
309                 ty::Generator(..) => {
310                     // Walk ALL the types in the generator: this will
311                     // include the upvar types as well as the yield
312                     // type. Note that this is mildly distinct from
313                     // the closure case, where we have to be careful
314                     // about the signature of the closure. We don't
315                     // have the problem of implied bounds here since
316                     // generators don't take arguments.
317                 }
318
319                 ty::Closure(def_id, substs) => {
320                     // Only check the upvar types for WF, not the rest
321                     // of the types within. This is needed because we
322                     // capture the signature and it may not be WF
323                     // without the implied bounds. Consider a closure
324                     // like `|x: &'a T|` -- it may be that `T: 'a` is
325                     // not known to hold in the creator's context (and
326                     // indeed the closure may not be invoked by its
327                     // creator, but rather turned to someone who *can*
328                     // verify that).
329                     //
330                     // The special treatment of closures here really
331                     // ought not to be necessary either; the problem
332                     // is related to #25860 -- there is no way for us
333                     // to express a fn type complete with the implied
334                     // bounds that it is assuming. I think in reality
335                     // the WF rules around fn are a bit messed up, and
336                     // that is the rot problem: `fn(&'a T)` should
337                     // probably always be WF, because it should be
338                     // shorthand for something like `where(T: 'a) {
339                     // fn(&'a T) }`, as discussed in #25860.
340                     //
341                     // Note that we are also skipping the generic
342                     // types. This is consistent with the `outlives`
343                     // code, but anyway doesn't matter: within the fn
344                     // body where they are created, the generics will
345                     // always be WF, and outside of that fn body we
346                     // are not directly inspecting closure types
347                     // anyway, except via auto trait matching (which
348                     // only inspects the upvar types).
349                     subtys.skip_current_subtree(); // subtree handled by compute_projection
350                     for upvar_ty in substs.upvar_tys(def_id, self.infcx.tcx) {
351                         self.compute(upvar_ty);
352                     }
353                 }
354
355                 ty::FnPtr(_) => {
356                     // let the loop iterate into the argument/return
357                     // types appearing in the fn signature
358                 }
359
360                 ty::Opaque(did, substs) => {
361                     // all of the requirements on type parameters
362                     // should've been checked by the instantiation
363                     // of whatever returned this exact `impl Trait`.
364
365                     // for named existential types we still need to check them
366                     if super::is_impl_trait_defn(self.infcx.tcx, did).is_none() {
367                         let obligations = self.nominal_obligations(did, substs);
368                         self.out.extend(obligations);
369                     }
370                 }
371
372                 ty::Dynamic(data, r) => {
373                     // WfObject
374                     //
375                     // Here, we defer WF checking due to higher-ranked
376                     // regions. This is perhaps not ideal.
377                     self.from_object_ty(ty, data, r);
378
379                     // FIXME(#27579) RFC also considers adding trait
380                     // obligations that don't refer to Self and
381                     // checking those
382
383                     let cause = self.cause(traits::MiscObligation);
384                     let component_traits =
385                         data.auto_traits().chain(data.principal_def_id());
386                     self.out.extend(
387                         component_traits.map(|did| traits::Obligation::new(
388                             cause.clone(),
389                             param_env,
390                             ty::Predicate::ObjectSafe(did)
391                         ))
392                     );
393                 }
394
395                 // Inference variables are the complicated case, since we don't
396                 // know what type they are. We do two things:
397                 //
398                 // 1. Check if they have been resolved, and if so proceed with
399                 //    THAT type.
400                 // 2. If not, check whether this is the type that we
401                 //    started with (ty0). In that case, we've made no
402                 //    progress at all, so return false. Otherwise,
403                 //    we've at least simplified things (i.e., we went
404                 //    from `Vec<$0>: WF` to `$0: WF`, so we can
405                 //    register a pending obligation and keep
406                 //    moving. (Goal is that an "inductive hypothesis"
407                 //    is satisfied to ensure termination.)
408                 ty::Infer(_) => {
409                     let ty = self.infcx.shallow_resolve(ty);
410                     if let ty::Infer(_) = ty.sty { // not yet resolved...
411                         if ty == ty0 { // ...this is the type we started from! no progress.
412                             return false;
413                         }
414
415                         let cause = self.cause(traits::MiscObligation);
416                         self.out.push( // ...not the type we started from, so we made progress.
417                             traits::Obligation::new(cause,
418                                                     self.param_env,
419                                                     ty::Predicate::WellFormed(ty)));
420                     } else {
421                         // Yes, resolved, proceed with the
422                         // result. Should never return false because
423                         // `ty` is not a Infer.
424                         assert!(self.compute(ty));
425                     }
426                 }
427             }
428         }
429
430         // if we made it through that loop above, we made progress!
431         return true;
432     }
433
434     fn nominal_obligations(&mut self,
435                            def_id: DefId,
436                            substs: SubstsRef<'tcx>)
437                            -> Vec<traits::PredicateObligation<'tcx>>
438     {
439         let predicates =
440             self.infcx.tcx.predicates_of(def_id)
441                           .instantiate(self.infcx.tcx, substs);
442         let cause = self.cause(traits::ItemObligation(def_id));
443         predicates.predicates
444                   .into_iter()
445                   .map(|pred| traits::Obligation::new(cause.clone(),
446                                                       self.param_env,
447                                                       pred))
448                   .filter(|pred| !pred.has_escaping_bound_vars())
449                   .collect()
450     }
451
452     fn from_object_ty(&mut self, ty: Ty<'tcx>,
453                       data: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
454                       region: ty::Region<'tcx>) {
455         // Imagine a type like this:
456         //
457         //     trait Foo { }
458         //     trait Bar<'c> : 'c { }
459         //
460         //     &'b (Foo+'c+Bar<'d>)
461         //         ^
462         //
463         // In this case, the following relationships must hold:
464         //
465         //     'b <= 'c
466         //     'd <= 'c
467         //
468         // The first conditions is due to the normal region pointer
469         // rules, which say that a reference cannot outlive its
470         // referent.
471         //
472         // The final condition may be a bit surprising. In particular,
473         // you may expect that it would have been `'c <= 'd`, since
474         // usually lifetimes of outer things are conservative
475         // approximations for inner things. However, it works somewhat
476         // differently with trait objects: here the idea is that if the
477         // user specifies a region bound (`'c`, in this case) it is the
478         // "master bound" that *implies* that bounds from other traits are
479         // all met. (Remember that *all bounds* in a type like
480         // `Foo+Bar+Zed` must be met, not just one, hence if we write
481         // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
482         // 'y.)
483         //
484         // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
485         // am looking forward to the future here.
486         if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
487             let implicit_bounds =
488                 object_region_bounds(self.infcx.tcx, data);
489
490             let explicit_bound = region;
491
492             self.out.reserve(implicit_bounds.len());
493             for implicit_bound in implicit_bounds {
494                 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
495                 let outlives = ty::Binder::dummy(
496                     ty::OutlivesPredicate(explicit_bound, implicit_bound));
497                 self.out.push(traits::Obligation::new(cause,
498                                                       self.param_env,
499                                                       outlives.to_predicate()));
500             }
501         }
502     }
503 }
504
505 /// Given an object type like `SomeTrait + Send`, computes the lifetime
506 /// bounds that must hold on the elided self type. These are derived
507 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
508 /// they declare `trait SomeTrait : 'static`, for example, then
509 /// `'static` would appear in the list. The hard work is done by
510 /// `ty::required_region_bounds`, see that for more information.
511 pub fn object_region_bounds<'a, 'gcx, 'tcx>(
512     tcx: TyCtxt<'a, 'gcx, 'tcx>,
513     existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
514     -> Vec<ty::Region<'tcx>>
515 {
516     // Since we don't actually *know* the self type for an object,
517     // this "open(err)" serves as a kind of dummy standin -- basically
518     // a placeholder type.
519     let open_ty = tcx.mk_infer(ty::FreshTy(0));
520
521     let predicates = existential_predicates.iter().filter_map(|predicate| {
522         if let ty::ExistentialPredicate::Projection(_) = *predicate.skip_binder() {
523             None
524         } else {
525             Some(predicate.with_self_ty(tcx, open_ty))
526         }
527     }).collect();
528
529     tcx.required_region_bounds(open_ty, predicates)
530 }