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