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