]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/wf.rs
Auto merge of #41684 - jethrogb:feature/ntstatus, r=alexcrichton
[rust.git] / src / librustc / ty / wf.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use hir::def_id::DefId;
12 use infer::InferCtxt;
13 use ty::outlives::Component;
14 use ty::subst::Substs;
15 use traits;
16 use ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable};
17 use std::iter::once;
18 use syntax::ast;
19 use syntax_pos::Span;
20 use middle::lang_items;
21
22 /// Returns the set of obligations needed to make `ty` well-formed.
23 /// If `ty` contains unresolved inference variables, this may include
24 /// further WF obligations. However, if `ty` IS an unresolved
25 /// inference variable, returns `None`, because we are not able to
26 /// make any progress at all. This is to prevent "livelock" where we
27 /// say "$0 is WF if $0 is WF".
28 pub fn obligations<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
29                                    body_id: ast::NodeId,
30                                    ty: Ty<'tcx>,
31                                    span: Span)
32                                    -> Option<Vec<traits::PredicateObligation<'tcx>>>
33 {
34     let mut wf = WfPredicates { infcx: infcx,
35                                 body_id: body_id,
36                                 span: span,
37                                 out: vec![] };
38     if wf.compute(ty) {
39         debug!("wf::obligations({:?}, body_id={:?}) = {:?}", ty, body_id, wf.out);
40         let result = wf.normalize();
41         debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", ty, body_id, result);
42         Some(result)
43     } else {
44         None // no progress made, return None
45     }
46 }
47
48 /// Returns the obligations that make this trait reference
49 /// well-formed.  For example, if there is a trait `Set` defined like
50 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
51 /// if `Bar: Eq`.
52 pub fn trait_obligations<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
53                                          body_id: ast::NodeId,
54                                          trait_ref: &ty::TraitRef<'tcx>,
55                                          span: Span)
56                                          -> Vec<traits::PredicateObligation<'tcx>>
57 {
58     let mut wf = WfPredicates { infcx: infcx, body_id: body_id, span: span, out: vec![] };
59     wf.compute_trait_ref(trait_ref);
60     wf.normalize()
61 }
62
63 pub fn predicate_obligations<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
64                                              body_id: ast::NodeId,
65                                              predicate: &ty::Predicate<'tcx>,
66                                              span: Span)
67                                              -> Vec<traits::PredicateObligation<'tcx>>
68 {
69     let mut wf = WfPredicates { infcx: infcx, body_id: body_id, span: span, out: vec![] };
70
71     // (*) ok to skip binders, because wf code is prepared for it
72     match *predicate {
73         ty::Predicate::Trait(ref t) => {
74             wf.compute_trait_ref(&t.skip_binder().trait_ref); // (*)
75         }
76         ty::Predicate::Equate(ref t) => {
77             wf.compute(t.skip_binder().0);
78             wf.compute(t.skip_binder().1);
79         }
80         ty::Predicate::RegionOutlives(..) => {
81         }
82         ty::Predicate::TypeOutlives(ref t) => {
83             wf.compute(t.skip_binder().0);
84         }
85         ty::Predicate::Projection(ref t) => {
86             let t = t.skip_binder(); // (*)
87             wf.compute_projection(t.projection_ty);
88             wf.compute(t.ty);
89         }
90         ty::Predicate::WellFormed(t) => {
91             wf.compute(t);
92         }
93         ty::Predicate::ObjectSafe(_) => {
94         }
95         ty::Predicate::ClosureKind(..) => {
96         }
97         ty::Predicate::Subtype(ref data) => {
98             wf.compute(data.skip_binder().a); // (*)
99             wf.compute(data.skip_binder().b); // (*)
100         }
101     }
102
103     wf.normalize()
104 }
105
106 /// Implied bounds are region relationships that we deduce
107 /// automatically.  The idea is that (e.g.) a caller must check that a
108 /// function's argument types are well-formed immediately before
109 /// calling that fn, and hence the *callee* can assume that its
110 /// argument types are well-formed. This may imply certain relationships
111 /// between generic parameters. For example:
112 ///
113 ///     fn foo<'a,T>(x: &'a T)
114 ///
115 /// can only be called with a `'a` and `T` such that `&'a T` is WF.
116 /// For `&'a T` to be WF, `T: 'a` must hold. So we can assume `T: 'a`.
117 #[derive(Debug)]
118 pub enum ImpliedBound<'tcx> {
119     RegionSubRegion(ty::Region<'tcx>, ty::Region<'tcx>),
120     RegionSubParam(ty::Region<'tcx>, ty::ParamTy),
121     RegionSubProjection(ty::Region<'tcx>, ty::ProjectionTy<'tcx>),
122 }
123
124 /// Compute the implied bounds that a callee/impl can assume based on
125 /// the fact that caller/projector has ensured that `ty` is WF.  See
126 /// the `ImpliedBound` type for more details.
127 pub fn implied_bounds<'a, 'gcx, 'tcx>(
128     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
129     body_id: ast::NodeId,
130     ty: Ty<'tcx>,
131     span: Span)
132     -> Vec<ImpliedBound<'tcx>>
133 {
134     // Sometimes when we ask what it takes for T: WF, we get back that
135     // U: WF is required; in that case, we push U onto this stack and
136     // process it next. Currently (at least) these resulting
137     // predicates are always guaranteed to be a subset of the original
138     // type, so we need not fear non-termination.
139     let mut wf_types = vec![ty];
140
141     let mut implied_bounds = vec![];
142
143     while let Some(ty) = wf_types.pop() {
144         // Compute the obligations for `ty` to be well-formed. If `ty` is
145         // an unresolved inference variable, just substituted an empty set
146         // -- because the return type here is going to be things we *add*
147         // to the environment, it's always ok for this set to be smaller
148         // than the ultimate set. (Note: normally there won't be
149         // unresolved inference variables here anyway, but there might be
150         // during typeck under some circumstances.)
151         let obligations = obligations(infcx, body_id, ty, span).unwrap_or(vec![]);
152
153         // From the full set of obligations, just filter down to the
154         // region relationships.
155         implied_bounds.extend(
156             obligations
157             .into_iter()
158             .flat_map(|obligation| {
159                 assert!(!obligation.has_escaping_regions());
160                 match obligation.predicate {
161                     ty::Predicate::Trait(..) |
162                     ty::Predicate::Equate(..) |
163                     ty::Predicate::Subtype(..) |
164                     ty::Predicate::Projection(..) |
165                     ty::Predicate::ClosureKind(..) |
166                     ty::Predicate::ObjectSafe(..) =>
167                         vec![],
168
169                     ty::Predicate::WellFormed(subty) => {
170                         wf_types.push(subty);
171                         vec![]
172                     }
173
174                     ty::Predicate::RegionOutlives(ref data) =>
175                         match infcx.tcx.no_late_bound_regions(data) {
176                             None =>
177                                 vec![],
178                             Some(ty::OutlivesPredicate(r_a, r_b)) =>
179                                 vec![ImpliedBound::RegionSubRegion(r_b, r_a)],
180                         },
181
182                     ty::Predicate::TypeOutlives(ref data) =>
183                         match infcx.tcx.no_late_bound_regions(data) {
184                             None => vec![],
185                             Some(ty::OutlivesPredicate(ty_a, r_b)) => {
186                                 let ty_a = infcx.resolve_type_vars_if_possible(&ty_a);
187                                 let components = infcx.tcx.outlives_components(ty_a);
188                                 implied_bounds_from_components(r_b, components)
189                             }
190                         },
191                 }}));
192     }
193
194     implied_bounds
195 }
196
197 /// When we have an implied bound that `T: 'a`, we can further break
198 /// this down to determine what relationships would have to hold for
199 /// `T: 'a` to hold. We get to assume that the caller has validated
200 /// those relationships.
201 fn implied_bounds_from_components<'tcx>(sub_region: ty::Region<'tcx>,
202                                         sup_components: Vec<Component<'tcx>>)
203                                         -> Vec<ImpliedBound<'tcx>>
204 {
205     sup_components
206         .into_iter()
207         .flat_map(|component| {
208             match component {
209                 Component::Region(r) =>
210                     vec![ImpliedBound::RegionSubRegion(sub_region, r)],
211                 Component::Param(p) =>
212                     vec![ImpliedBound::RegionSubParam(sub_region, p)],
213                 Component::Projection(p) =>
214                     vec![ImpliedBound::RegionSubProjection(sub_region, p)],
215                 Component::EscapingProjection(_) =>
216                     // If the projection has escaping regions, don't
217                     // try to infer any implied bounds even for its
218                     // free components. This is conservative, because
219                     // the caller will still have to prove that those
220                     // free components outlive `sub_region`. But the
221                     // idea is that the WAY that the caller proves
222                     // that may change in the future and we want to
223                     // give ourselves room to get smarter here.
224                     vec![],
225                 Component::UnresolvedInferenceVariable(..) =>
226                     vec![],
227             }
228         })
229         .collect()
230 }
231
232 struct WfPredicates<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
233     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
234     body_id: ast::NodeId,
235     span: Span,
236     out: Vec<traits::PredicateObligation<'tcx>>,
237 }
238
239 impl<'a, 'gcx, 'tcx> WfPredicates<'a, 'gcx, 'tcx> {
240     fn cause(&mut self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
241         traits::ObligationCause::new(self.span, self.body_id, code)
242     }
243
244     fn normalize(&mut self) -> Vec<traits::PredicateObligation<'tcx>> {
245         let cause = self.cause(traits::MiscObligation);
246         let infcx = &mut self.infcx;
247         self.out.iter()
248                 .inspect(|pred| assert!(!pred.has_escaping_regions()))
249                 .flat_map(|pred| {
250                     let mut selcx = traits::SelectionContext::new(infcx);
251                     let pred = traits::normalize(&mut selcx, cause.clone(), pred);
252                     once(pred.value).chain(pred.obligations)
253                 })
254                 .collect()
255     }
256
257     /// Pushes the obligations required for `trait_ref` to be WF into
258     /// `self.out`.
259     fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>) {
260         let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs);
261         self.out.extend(obligations);
262
263         let cause = self.cause(traits::MiscObligation);
264         self.out.extend(
265             trait_ref.substs.types()
266                             .filter(|ty| !ty.has_escaping_regions())
267                             .map(|ty| traits::Obligation::new(cause.clone(),
268                                                               ty::Predicate::WellFormed(ty))));
269     }
270
271     /// Pushes the obligations required for `trait_ref::Item` to be WF
272     /// into `self.out`.
273     fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
274         // A projection is well-formed if (a) the trait ref itself is
275         // WF and (b) the trait-ref holds.  (It may also be
276         // normalizable and be WF that way.)
277
278         self.compute_trait_ref(&data.trait_ref);
279
280         if !data.has_escaping_regions() {
281             let predicate = data.trait_ref.to_predicate();
282             let cause = self.cause(traits::ProjectionWf(data));
283             self.out.push(traits::Obligation::new(cause, predicate));
284         }
285     }
286
287     fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
288         if !subty.has_escaping_regions() {
289             let cause = self.cause(cause);
290             let trait_ref = ty::TraitRef {
291                 def_id: self.infcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
292                 substs: self.infcx.tcx.mk_substs_trait(subty, &[]),
293             };
294             self.out.push(traits::Obligation::new(cause, trait_ref.to_predicate()));
295         }
296     }
297
298     /// Push new obligations into `out`. Returns true if it was able
299     /// to generate all the predicates needed to validate that `ty0`
300     /// is WF. Returns false if `ty0` is an unresolved type variable,
301     /// in which case we are not able to simplify at all.
302     fn compute(&mut self, ty0: Ty<'tcx>) -> bool {
303         let mut subtys = ty0.walk();
304         while let Some(ty) = subtys.next() {
305             match ty.sty {
306                 ty::TyBool |
307                 ty::TyChar |
308                 ty::TyInt(..) |
309                 ty::TyUint(..) |
310                 ty::TyFloat(..) |
311                 ty::TyError |
312                 ty::TyStr |
313                 ty::TyNever |
314                 ty::TyParam(_) => {
315                     // WfScalar, WfParameter, etc
316                 }
317
318                 ty::TySlice(subty) |
319                 ty::TyArray(subty, _) => {
320                     self.require_sized(subty, traits::SliceOrArrayElem);
321                 }
322
323                 ty::TyTuple(ref tys, _) => {
324                     if let Some((_last, rest)) = tys.split_last() {
325                         for elem in rest {
326                             self.require_sized(elem, traits::TupleElem);
327                         }
328                     }
329                 }
330
331                 ty::TyRawPtr(_) => {
332                     // simple cases that are WF if their type args are WF
333                 }
334
335                 ty::TyProjection(data) => {
336                     subtys.skip_current_subtree(); // subtree handled by compute_projection
337                     self.compute_projection(data);
338                 }
339
340                 ty::TyAdt(def, substs) => {
341                     // WfNominalType
342                     let obligations = self.nominal_obligations(def.did, substs);
343                     self.out.extend(obligations);
344                 }
345
346                 ty::TyRef(r, mt) => {
347                     // WfReference
348                     if !r.has_escaping_regions() && !mt.ty.has_escaping_regions() {
349                         let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
350                         self.out.push(
351                             traits::Obligation::new(
352                                 cause,
353                                 ty::Predicate::TypeOutlives(
354                                     ty::Binder(
355                                         ty::OutlivesPredicate(mt.ty, r)))));
356                     }
357                 }
358
359                 ty::TyClosure(..) => {
360                     // the types in a closure are always the types of
361                     // local variables (or possibly references to local
362                     // variables), we'll walk those.
363                     //
364                     // (Though, local variables are probably not
365                     // needed, as they are separately checked w/r/t
366                     // WFedness.)
367                 }
368
369                 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
370                     // let the loop iterate into the argument/return
371                     // types appearing in the fn signature
372                 }
373
374                 ty::TyAnon(..) => {
375                     // all of the requirements on type parameters
376                     // should've been checked by the instantiation
377                     // of whatever returned this exact `impl Trait`.
378                 }
379
380                 ty::TyDynamic(data, r) => {
381                     // WfObject
382                     //
383                     // Here, we defer WF checking due to higher-ranked
384                     // regions. This is perhaps not ideal.
385                     self.from_object_ty(ty, data, r);
386
387                     // FIXME(#27579) RFC also considers adding trait
388                     // obligations that don't refer to Self and
389                     // checking those
390
391                     let cause = self.cause(traits::MiscObligation);
392
393                     let component_traits =
394                         data.auto_traits().chain(data.principal().map(|p| p.def_id()));
395                     self.out.extend(
396                         component_traits.map(|did| traits::Obligation::new(
397                             cause.clone(),
398                             ty::Predicate::ObjectSafe(did)
399                         ))
400                     );
401                 }
402
403                 // Inference variables are the complicated case, since we don't
404                 // know what type they are. We do two things:
405                 //
406                 // 1. Check if they have been resolved, and if so proceed with
407                 //    THAT type.
408                 // 2. If not, check whether this is the type that we
409                 //    started with (ty0). In that case, we've made no
410                 //    progress at all, so return false. Otherwise,
411                 //    we've at least simplified things (i.e., we went
412                 //    from `Vec<$0>: WF` to `$0: WF`, so we can
413                 //    register a pending obligation and keep
414                 //    moving. (Goal is that an "inductive hypothesis"
415                 //    is satisfied to ensure termination.)
416                 ty::TyInfer(_) => {
417                     let ty = self.infcx.shallow_resolve(ty);
418                     if let ty::TyInfer(_) = ty.sty { // not yet resolved...
419                         if ty == ty0 { // ...this is the type we started from! no progress.
420                             return false;
421                         }
422
423                         let cause = self.cause(traits::MiscObligation);
424                         self.out.push( // ...not the type we started from, so we made progress.
425                             traits::Obligation::new(cause, ty::Predicate::WellFormed(ty)));
426                     } else {
427                         // Yes, resolved, proceed with the
428                         // result. Should never return false because
429                         // `ty` is not a TyInfer.
430                         assert!(self.compute(ty));
431                     }
432                 }
433             }
434         }
435
436         // if we made it through that loop above, we made progress!
437         return true;
438     }
439
440     fn nominal_obligations(&mut self,
441                            def_id: DefId,
442                            substs: &Substs<'tcx>)
443                            -> Vec<traits::PredicateObligation<'tcx>>
444     {
445         let predicates =
446             self.infcx.tcx.predicates_of(def_id)
447                           .instantiate(self.infcx.tcx, substs);
448         let cause = self.cause(traits::ItemObligation(def_id));
449         predicates.predicates
450                   .into_iter()
451                   .map(|pred| traits::Obligation::new(cause.clone(), pred))
452                   .filter(|pred| !pred.has_escaping_regions())
453                   .collect()
454     }
455
456     fn from_object_ty(&mut self, ty: Ty<'tcx>,
457                       data: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>,
458                       region: ty::Region<'tcx>) {
459         // Imagine a type like this:
460         //
461         //     trait Foo { }
462         //     trait Bar<'c> : 'c { }
463         //
464         //     &'b (Foo+'c+Bar<'d>)
465         //         ^
466         //
467         // In this case, the following relationships must hold:
468         //
469         //     'b <= 'c
470         //     'd <= 'c
471         //
472         // The first conditions is due to the normal region pointer
473         // rules, which say that a reference cannot outlive its
474         // referent.
475         //
476         // The final condition may be a bit surprising. In particular,
477         // you may expect that it would have been `'c <= 'd`, since
478         // usually lifetimes of outer things are conservative
479         // approximations for inner things. However, it works somewhat
480         // differently with trait objects: here the idea is that if the
481         // user specifies a region bound (`'c`, in this case) it is the
482         // "master bound" that *implies* that bounds from other traits are
483         // all met. (Remember that *all bounds* in a type like
484         // `Foo+Bar+Zed` must be met, not just one, hence if we write
485         // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
486         // 'y.)
487         //
488         // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
489         // am looking forward to the future here.
490
491         if !data.has_escaping_regions() {
492             let implicit_bounds =
493                 object_region_bounds(self.infcx.tcx, data);
494
495             let explicit_bound = region;
496
497             for implicit_bound in implicit_bounds {
498                 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
499                 let outlives = ty::Binder(ty::OutlivesPredicate(explicit_bound, implicit_bound));
500                 self.out.push(traits::Obligation::new(cause, outlives.to_predicate()));
501             }
502         }
503     }
504 }
505
506 /// Given an object type like `SomeTrait+Send`, computes the lifetime
507 /// bounds that must hold on the elided self type. These are derived
508 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
509 /// they declare `trait SomeTrait : 'static`, for example, then
510 /// `'static` would appear in the list. The hard work is done by
511 /// `ty::required_region_bounds`, see that for more information.
512 pub fn object_region_bounds<'a, 'gcx, 'tcx>(
513     tcx: TyCtxt<'a, 'gcx, 'tcx>,
514     existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
515     -> Vec<ty::Region<'tcx>>
516 {
517     // Since we don't actually *know* the self type for an object,
518     // this "open(err)" serves as a kind of dummy standin -- basically
519     // a skolemized type.
520     let open_ty = tcx.mk_infer(ty::FreshTy(0));
521
522     let predicates = existential_predicates.iter().filter_map(|predicate| {
523         if let ty::ExistentialPredicate::Projection(_) = *predicate.skip_binder() {
524             None
525         } else {
526             Some(predicate.with_self_ty(tcx, open_ty))
527         }
528     }).collect();
529
530     tcx.required_region_bounds(open_ty, predicates)
531 }