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