]> git.proxmox.com Git - rustc.git/blame - src/librustc/ty/wf.rs
New upstream version 1.12.0+dfsg1
[rustc.git] / src / librustc / ty / wf.rs
CommitLineData
e9174d1e
SL
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
54a0048b
SL
11use hir::def_id::DefId;
12use infer::InferCtxt;
a7813a04 13use ty::outlives::Component;
54a0048b
SL
14use ty::subst::Substs;
15use traits;
16use ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable};
e9174d1e 17use std::iter::once;
e9174d1e 18use syntax::ast;
3157f602 19use syntax_pos::Span;
e9174d1e
SL
20use util::common::ErrorReported;
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".
a7813a04
XL
28pub 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>>>
e9174d1e
SL
33{
34 let mut wf = WfPredicates { infcx: infcx,
35 body_id: body_id,
36 span: span,
9cc50fc6 37 out: vec![] };
e9174d1e
SL
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`.
a7813a04
XL
52pub 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>>
e9174d1e 57{
9cc50fc6 58 let mut wf = WfPredicates { infcx: infcx, body_id: body_id, span: span, out: vec![] };
e9174d1e
SL
59 wf.compute_trait_ref(trait_ref);
60 wf.normalize()
61}
62
a7813a04
XL
63pub 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>>
e9174d1e 68{
9cc50fc6 69 let mut wf = WfPredicates { infcx: infcx, body_id: body_id, span: span, out: vec![] };
e9174d1e
SL
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 }
a7813a04
XL
95 ty::Predicate::ClosureKind(..) => {
96 }
97 ty::Predicate::Rfc1592(ref data) => {
98 bug!("RFC1592 predicate `{:?}` in predicate_obligations", data);
99 }
e9174d1e
SL
100 }
101
102 wf.normalize()
103}
104
105/// Implied bounds are region relationships that we deduce
106/// automatically. The idea is that (e.g.) a caller must check that a
107/// function's argument types are well-formed immediately before
108/// calling that fn, and hence the *callee* can assume that its
109/// argument types are well-formed. This may imply certain relationships
110/// between generic parameters. For example:
111///
112/// fn foo<'a,T>(x: &'a T)
113///
114/// can only be called with a `'a` and `T` such that `&'a T` is WF.
115/// For `&'a T` to be WF, `T: 'a` must hold. So we can assume `T: 'a`.
116#[derive(Debug)]
117pub enum ImpliedBound<'tcx> {
118 RegionSubRegion(ty::Region, ty::Region),
119 RegionSubParam(ty::Region, ty::ParamTy),
120 RegionSubProjection(ty::Region, ty::ProjectionTy<'tcx>),
121}
122
123/// Compute the implied bounds that a callee/impl can assume based on
124/// the fact that caller/projector has ensured that `ty` is WF. See
125/// the `ImpliedBound` type for more details.
a7813a04
XL
126pub fn implied_bounds<'a, 'gcx, 'tcx>(
127 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
e9174d1e
SL
128 body_id: ast::NodeId,
129 ty: Ty<'tcx>,
130 span: Span)
131 -> Vec<ImpliedBound<'tcx>>
132{
133 // Sometimes when we ask what it takes for T: WF, we get back that
134 // U: WF is required; in that case, we push U onto this stack and
135 // process it next. Currently (at least) these resulting
136 // predicates are always guaranteed to be a subset of the original
137 // type, so we need not fear non-termination.
138 let mut wf_types = vec![ty];
139
140 let mut implied_bounds = vec![];
141
142 while let Some(ty) = wf_types.pop() {
143 // Compute the obligations for `ty` to be well-formed. If `ty` is
144 // an unresolved inference variable, just substituted an empty set
145 // -- because the return type here is going to be things we *add*
146 // to the environment, it's always ok for this set to be smaller
147 // than the ultimate set. (Note: normally there won't be
148 // unresolved inference variables here anyway, but there might be
149 // during typeck under some circumstances.)
9cc50fc6 150 let obligations = obligations(infcx, body_id, ty, span).unwrap_or(vec![]);
e9174d1e
SL
151
152 // From the full set of obligations, just filter down to the
153 // region relationships.
154 implied_bounds.extend(
155 obligations
156 .into_iter()
157 .flat_map(|obligation| {
158 assert!(!obligation.has_escaping_regions());
159 match obligation.predicate {
160 ty::Predicate::Trait(..) |
a7813a04 161 ty::Predicate::Rfc1592(..) |
e9174d1e
SL
162 ty::Predicate::Equate(..) |
163 ty::Predicate::Projection(..) |
a7813a04 164 ty::Predicate::ClosureKind(..) |
e9174d1e
SL
165 ty::Predicate::ObjectSafe(..) =>
166 vec![],
167
168 ty::Predicate::WellFormed(subty) => {
169 wf_types.push(subty);
170 vec![]
171 }
172
173 ty::Predicate::RegionOutlives(ref data) =>
174 match infcx.tcx.no_late_bound_regions(data) {
175 None =>
176 vec![],
177 Some(ty::OutlivesPredicate(r_a, r_b)) =>
178 vec![ImpliedBound::RegionSubRegion(r_b, r_a)],
179 },
180
181 ty::Predicate::TypeOutlives(ref data) =>
182 match infcx.tcx.no_late_bound_regions(data) {
183 None => vec![],
184 Some(ty::OutlivesPredicate(ty_a, r_b)) => {
a7813a04 185 let components = infcx.outlives_components(ty_a);
e9174d1e
SL
186 implied_bounds_from_components(r_b, components)
187 }
188 },
189 }}));
190 }
191
192 implied_bounds
193}
194
195/// When we have an implied bound that `T: 'a`, we can further break
196/// this down to determine what relationships would have to hold for
197/// `T: 'a` to hold. We get to assume that the caller has validated
198/// those relationships.
199fn implied_bounds_from_components<'tcx>(sub_region: ty::Region,
200 sup_components: Vec<Component<'tcx>>)
201 -> Vec<ImpliedBound<'tcx>>
202{
203 sup_components
204 .into_iter()
205 .flat_map(|component| {
206 match component {
207 Component::Region(r) =>
208 vec!(ImpliedBound::RegionSubRegion(sub_region, r)),
209 Component::Param(p) =>
210 vec!(ImpliedBound::RegionSubParam(sub_region, p)),
211 Component::Projection(p) =>
212 vec!(ImpliedBound::RegionSubProjection(sub_region, p)),
213 Component::EscapingProjection(_) =>
214 // If the projection has escaping regions, don't
215 // try to infer any implied bounds even for its
216 // free components. This is conservative, because
217 // the caller will still have to prove that those
218 // free components outlive `sub_region`. But the
219 // idea is that the WAY that the caller proves
220 // that may change in the future and we want to
221 // give ourselves room to get smarter here.
222 vec!(),
223 Component::UnresolvedInferenceVariable(..) =>
224 vec!(),
e9174d1e
SL
225 }
226 })
227 .collect()
228}
229
a7813a04
XL
230struct WfPredicates<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
231 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
e9174d1e
SL
232 body_id: ast::NodeId,
233 span: Span,
234 out: Vec<traits::PredicateObligation<'tcx>>,
e9174d1e
SL
235}
236
a7813a04 237impl<'a, 'gcx, 'tcx> WfPredicates<'a, 'gcx, 'tcx> {
e9174d1e 238 fn cause(&mut self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
9cc50fc6 239 traits::ObligationCause::new(self.span, self.body_id, code)
e9174d1e
SL
240 }
241
242 fn normalize(&mut self) -> Vec<traits::PredicateObligation<'tcx>> {
243 let cause = self.cause(traits::MiscObligation);
244 let infcx = &mut self.infcx;
245 self.out.iter()
246 .inspect(|pred| assert!(!pred.has_escaping_regions()))
247 .flat_map(|pred| {
248 let mut selcx = traits::SelectionContext::new(infcx);
249 let pred = traits::normalize(&mut selcx, cause.clone(), pred);
250 once(pred.value).chain(pred.obligations)
251 })
252 .collect()
253 }
254
e9174d1e
SL
255 /// Pushes the obligations required for `trait_ref` to be WF into
256 /// `self.out`.
257 fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>) {
258 let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs);
259 self.out.extend(obligations);
260
261 let cause = self.cause(traits::MiscObligation);
262 self.out.extend(
263 trait_ref.substs.types
264 .as_slice()
265 .iter()
266 .filter(|ty| !ty.has_escaping_regions())
267 .map(|ty| traits::Obligation::new(cause.clone(),
268 ty::Predicate::WellFormed(ty))));
269 }
270
271 /// Pushes the obligations required for `trait_ref::Item` to be WF
272 /// into `self.out`.
273 fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
274 // A projection is well-formed if (a) the trait ref itself is
a7813a04 275 // WF and (b) the trait-ref holds. (It may also be
e9174d1e
SL
276 // normalizable and be WF that way.)
277
278 self.compute_trait_ref(&data.trait_ref);
279
280 if !data.has_escaping_regions() {
281 let predicate = data.trait_ref.to_predicate();
282 let cause = self.cause(traits::ProjectionWf(data));
283 self.out.push(traits::Obligation::new(cause, predicate));
284 }
285 }
286
a7813a04
XL
287 fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>,
288 rfc1592: bool) {
289 if !subty.has_escaping_regions() {
290 let cause = self.cause(cause);
291 match self.infcx.tcx.trait_ref_for_builtin_bound(ty::BoundSized, subty) {
292 Ok(trait_ref) => {
293 let predicate = trait_ref.to_predicate();
294 let predicate = if rfc1592 {
295 ty::Predicate::Rfc1592(box predicate)
296 } else {
297 predicate
298 };
299 self.out.push(
300 traits::Obligation::new(cause,
301 predicate));
302 }
303 Err(ErrorReported) => { }
304 }
305 }
306 }
307
e9174d1e
SL
308 /// Push new obligations into `out`. Returns true if it was able
309 /// to generate all the predicates needed to validate that `ty0`
310 /// is WF. Returns false if `ty0` is an unresolved type variable,
311 /// in which case we are not able to simplify at all.
312 fn compute(&mut self, ty0: Ty<'tcx>) -> bool {
a7813a04 313 let tcx = self.infcx.tcx;
e9174d1e
SL
314 let mut subtys = ty0.walk();
315 while let Some(ty) = subtys.next() {
316 match ty.sty {
317 ty::TyBool |
318 ty::TyChar |
319 ty::TyInt(..) |
320 ty::TyUint(..) |
321 ty::TyFloat(..) |
322 ty::TyError |
323 ty::TyStr |
5bcae85e 324 ty::TyNever |
e9174d1e
SL
325 ty::TyParam(_) => {
326 // WfScalar, WfParameter, etc
327 }
328
329 ty::TySlice(subty) |
330 ty::TyArray(subty, _) => {
a7813a04
XL
331 self.require_sized(subty, traits::SliceOrArrayElem, false);
332 }
333
334 ty::TyTuple(ref tys) => {
335 if let Some((_last, rest)) = tys.split_last() {
336 for elem in rest {
337 self.require_sized(elem, traits::TupleElem, true);
e9174d1e 338 }
9cc50fc6 339 }
e9174d1e
SL
340 }
341
342 ty::TyBox(_) |
e9174d1e
SL
343 ty::TyRawPtr(_) => {
344 // simple cases that are WF if their type args are WF
345 }
346
347 ty::TyProjection(data) => {
348 subtys.skip_current_subtree(); // subtree handled by compute_projection
349 self.compute_projection(data);
350 }
351
352 ty::TyEnum(def, substs) |
353 ty::TyStruct(def, substs) => {
354 // WfNominalType
355 let obligations = self.nominal_obligations(def.did, substs);
356 self.out.extend(obligations);
357 }
358
359 ty::TyRef(r, mt) => {
360 // WfReference
361 if !r.has_escaping_regions() && !mt.ty.has_escaping_regions() {
362 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
363 self.out.push(
364 traits::Obligation::new(
365 cause,
366 ty::Predicate::TypeOutlives(
367 ty::Binder(
368 ty::OutlivesPredicate(mt.ty, *r)))));
369 }
370 }
371
372 ty::TyClosure(..) => {
373 // the types in a closure are always the types of
374 // local variables (or possibly references to local
9cc50fc6
SL
375 // variables), we'll walk those.
376 //
377 // (Though, local variables are probably not
378 // needed, as they are separately checked w/r/t
379 // WFedness.)
e9174d1e
SL
380 }
381
54a0048b
SL
382 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
383 // let the loop iterate into the argument/return
9cc50fc6 384 // types appearing in the fn signature
e9174d1e
SL
385 }
386
5bcae85e
SL
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
e9174d1e
SL
393 ty::TyTrait(ref data) => {
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);
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);
a7813a04
XL
405
406 // FIXME(#33243): remove RFC1592
407 self.out.push(traits::Obligation::new(
408 cause.clone(),
409 ty::Predicate::ObjectSafe(data.principal_def_id())
410 ));
411 let component_traits =
412 data.bounds.builtin_bounds.iter().flat_map(|bound| {
413 tcx.lang_items.from_builtin_kind(bound).ok()
414 });
415// .chain(Some(data.principal_def_id()));
416 self.out.extend(
417 component_traits.map(|did| { traits::Obligation::new(
418 cause.clone(),
419 ty::Predicate::Rfc1592(
420 box ty::Predicate::ObjectSafe(did)
421 )
422 )})
423 );
e9174d1e
SL
424 }
425
426 // Inference variables are the complicated case, since we don't
427 // know what type they are. We do two things:
428 //
429 // 1. Check if they have been resolved, and if so proceed with
430 // THAT type.
431 // 2. If not, check whether this is the type that we
432 // started with (ty0). In that case, we've made no
433 // progress at all, so return false. Otherwise,
434 // we've at least simplified things (i.e., we went
435 // from `Vec<$0>: WF` to `$0: WF`, so we can
436 // register a pending obligation and keep
437 // moving. (Goal is that an "inductive hypothesis"
438 // is satisfied to ensure termination.)
439 ty::TyInfer(_) => {
440 let ty = self.infcx.shallow_resolve(ty);
441 if let ty::TyInfer(_) = ty.sty { // not yet resolved...
442 if ty == ty0 { // ...this is the type we started from! no progress.
443 return false;
444 }
445
446 let cause = self.cause(traits::MiscObligation);
447 self.out.push( // ...not the type we started from, so we made progress.
448 traits::Obligation::new(cause, ty::Predicate::WellFormed(ty)));
449 } else {
450 // Yes, resolved, proceed with the
451 // result. Should never return false because
452 // `ty` is not a TyInfer.
453 assert!(self.compute(ty));
454 }
455 }
456 }
457 }
458
459 // if we made it through that loop above, we made progress!
460 return true;
461 }
462
463 fn nominal_obligations(&mut self,
464 def_id: DefId,
465 substs: &Substs<'tcx>)
466 -> Vec<traits::PredicateObligation<'tcx>>
467 {
468 let predicates =
469 self.infcx.tcx.lookup_predicates(def_id)
470 .instantiate(self.infcx.tcx, substs);
471 let cause = self.cause(traits::ItemObligation(def_id));
472 predicates.predicates
473 .into_iter()
474 .map(|pred| traits::Obligation::new(cause.clone(), pred))
475 .filter(|pred| !pred.has_escaping_regions())
476 .collect()
477 }
478
479 fn from_object_ty(&mut self, ty: Ty<'tcx>, data: &ty::TraitTy<'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,
515 &data.principal,
516 data.bounds.builtin_bounds);
517
518 let explicit_bound = data.bounds.region_bound;
519
520 for implicit_bound in implicit_bounds {
521 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
522 let outlives = ty::Binder(ty::OutlivesPredicate(explicit_bound, implicit_bound));
523 self.out.push(traits::Obligation::new(cause, 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.
a7813a04
XL
535pub fn object_region_bounds<'a, 'gcx, 'tcx>(
536 tcx: TyCtxt<'a, 'gcx, 'tcx>,
e9174d1e
SL
537 principal: &ty::PolyTraitRef<'tcx>,
538 others: ty::BuiltinBounds)
539 -> Vec<ty::Region>
540{
541 // Since we don't actually *know* the self type for an object,
542 // this "open(err)" serves as a kind of dummy standin -- basically
543 // a skolemized type.
544 let open_ty = tcx.mk_infer(ty::FreshTy(0));
545
546 // Note that we preserve the overall binding levels here.
547 assert!(!open_ty.has_escaping_regions());
548 let substs = tcx.mk_substs(principal.0.substs.with_self_ty(open_ty));
549 let trait_refs = vec!(ty::Binder(ty::TraitRef::new(principal.0.def_id, substs)));
550
551 let mut predicates = others.to_predicates(tcx, open_ty);
552 predicates.extend(trait_refs.iter().map(|t| t.to_predicate()));
553
554 tcx.required_region_bounds(open_ty, predicates)
555}