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