1 // Copyright 2012-2014 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.
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.
11 //! The region check is a final pass that runs over the AST after we have
12 //! inferred the type constraints but before we have actually finalized
13 //! the types. Its purpose is to embed a variety of region constraints.
14 //! Inserting these constraints as a separate pass is good because (1) it
15 //! localizes the code that has to do with region inference and (2) often
16 //! we cannot know what constraints are needed until the basic types have
19 //! ### Interaction with the borrow checker
21 //! In general, the job of the borrowck module (which runs later) is to
22 //! check that all soundness criteria are met, given a particular set of
23 //! regions. The job of *this* module is to anticipate the needs of the
24 //! borrow checker and infer regions that will satisfy its requirements.
25 //! It is generally true that the inference doesn't need to be sound,
26 //! meaning that if there is a bug and we inferred bad regions, the borrow
27 //! checker should catch it. This is not entirely true though; for
28 //! example, the borrow checker doesn't check subtyping, and it doesn't
29 //! check that region pointers are always live when they are used. It
30 //! might be worthwhile to fix this so that borrowck serves as a kind of
31 //! verification step -- that would add confidence in the overall
32 //! correctness of the compiler, at the cost of duplicating some type
33 //! checks and effort.
35 //! ### Inferring the duration of borrows, automatic and otherwise
37 //! Whenever we introduce a borrowed pointer, for example as the result of
38 //! a borrow expression `let x = &data`, the lifetime of the pointer `x`
39 //! is always specified as a region inference variable. `regionck` has the
40 //! job of adding constraints such that this inference variable is as
41 //! narrow as possible while still accommodating all uses (that is, every
42 //! dereference of the resulting pointer must be within the lifetime).
46 //! Generally speaking, `regionck` does NOT try to ensure that the data
47 //! `data` will outlive the pointer `x`. That is the job of borrowck. The
48 //! one exception is when "re-borrowing" the contents of another borrowed
49 //! pointer. For example, imagine you have a borrowed pointer `b` with
50 //! lifetime L1 and you have an expression `&*b`. The result of this
51 //! expression will be another borrowed pointer with lifetime L2 (which is
52 //! an inference variable). The borrow checker is going to enforce the
53 //! constraint that L2 < L1, because otherwise you are re-borrowing data
54 //! for a lifetime larger than the original loan. However, without the
55 //! routines in this module, the region inferencer would not know of this
56 //! dependency and thus it might infer the lifetime of L2 to be greater
57 //! than L1 (issue #3148).
59 //! There are a number of troublesome scenarios in the tests
60 //! `region-dependent-*.rs`, but here is one example:
62 //! struct Foo { i: i32 }
63 //! struct Bar { foo: Foo }
64 //! fn get_i<'a>(x: &'a Bar) -> &'a i32 {
65 //! let foo = &x.foo; // Lifetime L1
66 //! &foo.i // Lifetime L2
69 //! Note that this comes up either with `&` expressions, `ref`
70 //! bindings, and `autorefs`, which are the three ways to introduce
73 //! The key point here is that when you are borrowing a value that
74 //! is "guaranteed" by a borrowed pointer, you must link the
75 //! lifetime of that borrowed pointer (L1, here) to the lifetime of
76 //! the borrow itself (L2). What do I mean by "guaranteed" by a
77 //! borrowed pointer? I mean any data that is reached by first
78 //! dereferencing a borrowed pointer and then either traversing
79 //! interior offsets or boxes. We say that the guarantor
80 //! of such data is the region of the borrowed pointer that was
81 //! traversed. This is essentially the same as the ownership
82 //! relation, except that a borrowed pointer never owns its
87 use middle::free_region::FreeRegionMap;
88 use middle::mem_categorization as mc;
89 use middle::mem_categorization::Categorization;
90 use middle::region::{CodeExtent, RegionMaps};
91 use rustc::hir::def_id::DefId;
92 use rustc::ty::subst::Substs;
94 use rustc::ty::{self, Ty, TypeFoldable};
95 use rustc::infer::{self, GenericKind, SubregionOrigin, VerifyBound};
96 use rustc::ty::adjustment;
97 use rustc::ty::outlives::Component;
104 use syntax_pos::Span;
105 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
106 use rustc::hir::{self, PatKind};
108 // a variation on try that just returns unit
109 macro_rules! ignore_err {
110 ($e:expr) => (match $e { Ok(e) => e, Err(_) => return () })
113 ///////////////////////////////////////////////////////////////////////////
114 // PUBLIC ENTRY POINTS
116 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
117 pub fn regionck_expr(&self, body: &'gcx hir::Body) {
118 let subject = self.tcx.hir.body_owner_def_id(body.id());
119 let id = body.value.id;
120 let mut rcx = RegionCtxt::new(self, RepeatingScope(id), id, Subject(subject));
121 if self.err_count_since_creation() == 0 {
122 // regionck assumes typeck succeeded
123 rcx.visit_body(body);
124 rcx.visit_region_obligations(id);
126 rcx.resolve_regions_and_report_errors();
128 assert!(self.tables.borrow().free_region_map.is_empty());
129 self.tables.borrow_mut().free_region_map = rcx.free_region_map;
132 /// Region checking during the WF phase for items. `wf_tys` are the
133 /// types from which we should derive implied bounds, if any.
134 pub fn regionck_item(&self,
135 item_id: ast::NodeId,
137 wf_tys: &[Ty<'tcx>]) {
138 debug!("regionck_item(item.id={:?}, wf_tys={:?}", item_id, wf_tys);
139 let subject = self.tcx.hir.local_def_id(item_id);
140 let mut rcx = RegionCtxt::new(self, RepeatingScope(item_id), item_id, Subject(subject));
141 rcx.free_region_map.relate_free_regions_from_predicates(
142 &self.param_env.caller_bounds);
143 rcx.relate_free_regions(wf_tys, item_id, span);
144 rcx.visit_region_obligations(item_id);
145 rcx.resolve_regions_and_report_errors();
148 pub fn regionck_fn(&self,
150 body: &'gcx hir::Body) {
151 debug!("regionck_fn(id={})", fn_id);
152 let subject = self.tcx.hir.body_owner_def_id(body.id());
153 let node_id = body.value.id;
154 let mut rcx = RegionCtxt::new(self, RepeatingScope(node_id), node_id, Subject(subject));
156 if self.err_count_since_creation() == 0 {
157 // regionck assumes typeck succeeded
158 rcx.visit_fn_body(fn_id, body, self.tcx.hir.span(fn_id));
161 rcx.free_region_map.relate_free_regions_from_predicates(
162 &self.param_env.caller_bounds);
164 rcx.resolve_regions_and_report_errors();
166 // In this mode, we also copy the free-region-map into the
167 // tables of the enclosing fcx. In the other regionck modes
168 // (e.g., `regionck_item`), we don't have an enclosing tables.
169 assert!(self.tables.borrow().free_region_map.is_empty());
170 self.tables.borrow_mut().free_region_map = rcx.free_region_map;
174 ///////////////////////////////////////////////////////////////////////////
177 pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
178 pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
180 region_bound_pairs: Vec<(ty::Region<'tcx>, GenericKind<'tcx>)>,
182 pub region_maps: Rc<RegionMaps>,
184 free_region_map: FreeRegionMap<'tcx>,
186 // id of innermost fn body id
187 body_id: ast::NodeId,
189 // call_site scope of innermost fn
190 call_site_scope: Option<CodeExtent>,
192 // id of innermost fn or loop
193 repeating_scope: ast::NodeId,
195 // id of AST node being analyzed (the subject of the analysis).
196 subject_def_id: DefId,
200 /// Implied bounds are region relationships that we deduce
201 /// automatically. The idea is that (e.g.) a caller must check that a
202 /// function's argument types are well-formed immediately before
203 /// calling that fn, and hence the *callee* can assume that its
204 /// argument types are well-formed. This may imply certain relationships
205 /// between generic parameters. For example:
207 /// fn foo<'a,T>(x: &'a T)
209 /// can only be called with a `'a` and `T` such that `&'a T` is WF.
210 /// For `&'a T` to be WF, `T: 'a` must hold. So we can assume `T: 'a`.
212 enum ImpliedBound<'tcx> {
213 RegionSubRegion(ty::Region<'tcx>, ty::Region<'tcx>),
214 RegionSubParam(ty::Region<'tcx>, ty::ParamTy),
215 RegionSubProjection(ty::Region<'tcx>, ty::ProjectionTy<'tcx>),
218 impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> {
219 type Target = FnCtxt<'a, 'gcx, 'tcx>;
220 fn deref(&self) -> &Self::Target {
225 pub struct RepeatingScope(ast::NodeId);
226 pub struct Subject(DefId);
228 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
229 pub fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
230 RepeatingScope(initial_repeating_scope): RepeatingScope,
231 initial_body_id: ast::NodeId,
232 Subject(subject): Subject) -> RegionCtxt<'a, 'gcx, 'tcx> {
233 let region_maps = fcx.tcx.region_maps(subject);
236 region_maps: region_maps,
237 repeating_scope: initial_repeating_scope,
238 body_id: initial_body_id,
239 call_site_scope: None,
240 subject_def_id: subject,
241 region_bound_pairs: Vec::new(),
242 free_region_map: FreeRegionMap::new(),
246 fn set_call_site_scope(&mut self, call_site_scope: Option<CodeExtent>)
247 -> Option<CodeExtent> {
248 mem::replace(&mut self.call_site_scope, call_site_scope)
251 fn set_body_id(&mut self, body_id: ast::NodeId) -> ast::NodeId {
252 mem::replace(&mut self.body_id, body_id)
255 fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId {
256 mem::replace(&mut self.repeating_scope, scope)
259 /// Try to resolve the type for the given node, returning t_err if an error results. Note that
260 /// we never care about the details of the error, the same error will be detected and reported
261 /// in the writeback phase.
263 /// Note one important point: we do not attempt to resolve *region variables* here. This is
264 /// because regionck is essentially adding constraints to those region variables and so may yet
265 /// influence how they are resolved.
267 /// Consider this silly example:
270 /// fn borrow(x: &i32) -> &i32 {x}
271 /// fn foo(x: @i32) -> i32 { // block: B
272 /// let b = borrow(x); // region: <R0>
277 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
278 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
279 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
280 /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
281 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
282 pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
283 self.resolve_type_vars_if_possible(&unresolved_ty)
286 /// Try to resolve the type for the given node.
287 fn resolve_node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
288 let t = self.node_ty(id);
292 /// Try to resolve the type for the given node.
293 pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> {
294 let ty = self.tables.borrow().expr_ty_adjusted(expr);
295 self.resolve_type(ty)
298 fn visit_fn_body(&mut self,
299 id: ast::NodeId, // the id of the fn itself
300 body: &'gcx hir::Body,
303 // When we enter a function, we can derive
304 debug!("visit_fn_body(id={})", id);
306 let body_id = body.id();
308 let call_site = CodeExtent::CallSiteScope(body_id);
309 let old_call_site_scope = self.set_call_site_scope(Some(call_site));
312 let fn_sig_map = &self.tables.borrow().liberated_fn_sigs;
313 match fn_sig_map.get(&id) {
314 Some(f) => f.clone(),
316 bug!("No fn-sig entry for id={}", id);
321 let old_region_bounds_pairs_len = self.region_bound_pairs.len();
323 // Collect the types from which we create inferred bounds.
324 // For the return type, if diverging, substitute `bool` just
325 // because it will have no effect.
327 // FIXME(#27579) return types should not be implied bounds
328 let fn_sig_tys: Vec<_> =
329 fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
331 let old_body_id = self.set_body_id(body_id.node_id);
332 self.relate_free_regions(&fn_sig_tys[..], body_id.node_id, span);
333 self.link_fn_args(CodeExtent::Misc(body_id.node_id), &body.arguments);
334 self.visit_body(body);
335 self.visit_region_obligations(body_id.node_id);
337 let call_site_scope = self.call_site_scope.unwrap();
338 debug!("visit_fn_body body.id {:?} call_site_scope: {:?}",
339 body.id(), call_site_scope);
340 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope));
341 self.type_of_node_must_outlive(infer::CallReturn(span),
345 self.region_bound_pairs.truncate(old_region_bounds_pairs_len);
347 self.set_body_id(old_body_id);
348 self.set_call_site_scope(old_call_site_scope);
351 fn visit_region_obligations(&mut self, node_id: ast::NodeId)
353 debug!("visit_region_obligations: node_id={}", node_id);
355 // region checking can introduce new pending obligations
356 // which, when processed, might generate new region
357 // obligations. So make sure we process those.
358 self.select_all_obligations_or_error();
360 // Make a copy of the region obligations vec because we'll need
361 // to be able to borrow the fulfillment-cx below when projecting.
362 let region_obligations =
365 .region_obligations(node_id)
368 for r_o in ®ion_obligations {
369 debug!("visit_region_obligations: r_o={:?} cause={:?}",
371 let sup_type = self.resolve_type(r_o.sup_type);
372 let origin = self.code_to_origin(&r_o.cause, sup_type);
373 self.type_must_outlive(origin, sup_type, r_o.sub_region);
376 // Processing the region obligations should not cause the list to grow further:
377 assert_eq!(region_obligations.len(),
378 self.fulfillment_cx.borrow().region_obligations(node_id).len());
381 fn code_to_origin(&self,
382 cause: &traits::ObligationCause<'tcx>,
384 -> SubregionOrigin<'tcx> {
385 SubregionOrigin::from_obligation_cause(cause,
386 || infer::RelateParamBound(cause.span, sup_type))
389 /// This method populates the region map's `free_region_map`. It walks over the transformed
390 /// argument and return types for each function just before we check the body of that function,
391 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
392 /// [usize]`. We do not allow references to outlive the things they point at, so we can assume
393 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
394 /// the caller side, the caller is responsible for checking that the type of every expression
395 /// (including the actual values for the arguments, as well as the return type of the fn call)
398 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
399 fn relate_free_regions(&mut self,
400 fn_sig_tys: &[Ty<'tcx>],
401 body_id: ast::NodeId,
403 debug!("relate_free_regions >>");
405 for &ty in fn_sig_tys {
406 let ty = self.resolve_type(ty);
407 debug!("relate_free_regions(t={:?})", ty);
408 let implied_bounds = self.implied_bounds(body_id, ty, span);
410 // But also record other relationships, such as `T:'x`,
411 // that don't go into the free-region-map but which we use
413 for implication in implied_bounds {
414 debug!("implication: {:?}", implication);
416 ImpliedBound::RegionSubRegion(r_a @ &ty::ReEarlyBound(_),
418 ImpliedBound::RegionSubRegion(r_a @ &ty::ReFree(_),
419 &ty::ReVar(vid_b)) => {
420 self.add_given(r_a, vid_b);
422 ImpliedBound::RegionSubParam(r_a, param_b) => {
423 self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
425 ImpliedBound::RegionSubProjection(r_a, projection_b) => {
426 self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
428 ImpliedBound::RegionSubRegion(r_a, r_b) => {
429 // In principle, we could record (and take
430 // advantage of) every relationship here, but
431 // we are also free not to -- it simply means
432 // strictly less that we can successfully type
433 // check. Right now we only look for things
434 // relationships between free regions. (It may
435 // also be that we should revise our inference
436 // system to be more general and to make use
437 // of *every* relationship that arises here,
438 // but presently we do not.)
439 self.free_region_map.relate_regions(r_a, r_b);
445 debug!("<< relate_free_regions");
448 /// Compute the implied bounds that a callee/impl can assume based on
449 /// the fact that caller/projector has ensured that `ty` is WF. See
450 /// the `ImpliedBound` type for more details.
451 fn implied_bounds(&mut self, body_id: ast::NodeId, ty: Ty<'tcx>, span: Span)
452 -> Vec<ImpliedBound<'tcx>> {
453 // Sometimes when we ask what it takes for T: WF, we get back that
454 // U: WF is required; in that case, we push U onto this stack and
455 // process it next. Currently (at least) these resulting
456 // predicates are always guaranteed to be a subset of the original
457 // type, so we need not fear non-termination.
458 let mut wf_types = vec![ty];
460 let mut implied_bounds = vec![];
462 while let Some(ty) = wf_types.pop() {
463 // Compute the obligations for `ty` to be well-formed. If `ty` is
464 // an unresolved inference variable, just substituted an empty set
465 // -- because the return type here is going to be things we *add*
466 // to the environment, it's always ok for this set to be smaller
467 // than the ultimate set. (Note: normally there won't be
468 // unresolved inference variables here anyway, but there might be
469 // during typeck under some circumstances.)
471 wf::obligations(self, self.fcx.param_env, body_id, ty, span)
474 // NB: All of these predicates *ought* to be easily proven
475 // true. In fact, their correctness is (mostly) implied by
476 // other parts of the program. However, in #42552, we had
477 // an annoying scenario where:
479 // - Some `T::Foo` gets normalized, resulting in a
480 // variable `_1` and a `T: Trait<Foo=_1>` constraint
481 // (not sure why it couldn't immediately get
482 // solved). This result of `_1` got cached.
483 // - These obligations were dropped on the floor here,
484 // rather than being registered.
485 // - Then later we would get a request to normalize
486 // `T::Foo` which would result in `_1` being used from
487 // the cache, but hence without the `T: Trait<Foo=_1>`
488 // constraint. As a result, `_1` never gets resolved,
489 // and we get an ICE (in dropck).
491 // Therefore, we register any predicates involving
492 // inference variables. We restrict ourselves to those
493 // involving inference variables both for efficiency and
494 // to avoids duplicate errors that otherwise show up.
495 self.fcx.register_predicates(
497 .filter(|o| o.predicate.has_infer_types())
500 // From the full set of obligations, just filter down to the
501 // region relationships.
502 implied_bounds.extend(
505 .flat_map(|obligation| {
506 assert!(!obligation.has_escaping_regions());
507 match obligation.predicate {
508 ty::Predicate::Trait(..) |
509 ty::Predicate::Equate(..) |
510 ty::Predicate::Subtype(..) |
511 ty::Predicate::Projection(..) |
512 ty::Predicate::ClosureKind(..) |
513 ty::Predicate::ObjectSafe(..) =>
516 ty::Predicate::WellFormed(subty) => {
517 wf_types.push(subty);
521 ty::Predicate::RegionOutlives(ref data) =>
522 match self.tcx.no_late_bound_regions(data) {
525 Some(ty::OutlivesPredicate(r_a, r_b)) =>
526 vec![ImpliedBound::RegionSubRegion(r_b, r_a)],
529 ty::Predicate::TypeOutlives(ref data) =>
530 match self.tcx.no_late_bound_regions(data) {
532 Some(ty::OutlivesPredicate(ty_a, r_b)) => {
533 let ty_a = self.resolve_type_vars_if_possible(&ty_a);
534 let components = self.tcx.outlives_components(ty_a);
535 self.implied_bounds_from_components(r_b, components)
544 /// When we have an implied bound that `T: 'a`, we can further break
545 /// this down to determine what relationships would have to hold for
546 /// `T: 'a` to hold. We get to assume that the caller has validated
547 /// those relationships.
548 fn implied_bounds_from_components(&self,
549 sub_region: ty::Region<'tcx>,
550 sup_components: Vec<Component<'tcx>>)
551 -> Vec<ImpliedBound<'tcx>>
555 .flat_map(|component| {
557 Component::Region(r) =>
558 vec![ImpliedBound::RegionSubRegion(sub_region, r)],
559 Component::Param(p) =>
560 vec![ImpliedBound::RegionSubParam(sub_region, p)],
561 Component::Projection(p) =>
562 vec![ImpliedBound::RegionSubProjection(sub_region, p)],
563 Component::EscapingProjection(_) =>
564 // If the projection has escaping regions, don't
565 // try to infer any implied bounds even for its
566 // free components. This is conservative, because
567 // the caller will still have to prove that those
568 // free components outlive `sub_region`. But the
569 // idea is that the WAY that the caller proves
570 // that may change in the future and we want to
571 // give ourselves room to get smarter here.
573 Component::UnresolvedInferenceVariable(..) =>
580 fn resolve_regions_and_report_errors(&self) {
581 self.fcx.resolve_regions_and_report_errors(self.subject_def_id,
583 &self.free_region_map);
586 fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) {
587 debug!("regionck::visit_pat(pat={:?})", pat);
588 pat.each_binding(|_, id, span, _| {
589 // If we have a variable that contains region'd data, that
590 // data will be accessible from anywhere that the variable is
591 // accessed. We must be wary of loops like this:
593 // // from src/test/compile-fail/borrowck-lend-flow.rs
594 // let mut v = box 3, w = box 4;
595 // let mut x = &mut w;
598 // borrow(v); //~ ERROR cannot borrow
599 // x = &mut v; // (1)
602 // Typically, we try to determine the region of a borrow from
603 // those points where it is dereferenced. In this case, one
604 // might imagine that the lifetime of `x` need only be the
605 // body of the loop. But of course this is incorrect because
606 // the pointer that is created at point (1) is consumed at
607 // point (2), meaning that it must be live across the loop
608 // iteration. The easiest way to guarantee this is to require
609 // that the lifetime of any regions that appear in a
610 // variable's type enclose at least the variable's scope.
612 let var_scope = self.region_maps.var_scope(id);
613 let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
615 let origin = infer::BindingTypeIsNotValidAtDecl(span);
616 self.type_of_node_must_outlive(origin, id, var_region);
618 let typ = self.resolve_node_type(id);
619 let _ = dropck::check_safety_of_destructor_if_necessary(
620 self, typ, span, var_scope);
625 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for RegionCtxt<'a, 'gcx, 'tcx> {
626 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
627 // However, right now we run into an issue whereby some free
628 // regions are not properly related if they appear within the
629 // types of arguments that must be inferred. This could be
630 // addressed by deferring the construction of the region
631 // hierarchy, and in particular the relationships between free
632 // regions, until regionck, as described in #3238.
634 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
635 NestedVisitorMap::None
638 fn visit_fn(&mut self, _fk: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
639 b: hir::BodyId, span: Span, id: ast::NodeId) {
640 let body = self.tcx.hir.body(b);
641 self.visit_fn_body(id, body, span)
644 //visit_pat: visit_pat, // (..) see above
646 fn visit_arm(&mut self, arm: &'gcx hir::Arm) {
649 self.constrain_bindings_in_pat(p);
651 intravisit::walk_arm(self, arm);
654 fn visit_local(&mut self, l: &'gcx hir::Local) {
656 self.constrain_bindings_in_pat(&l.pat);
658 intravisit::walk_local(self, l);
661 fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
662 debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
663 expr, self.repeating_scope);
665 // No matter what, the type of each expression must outlive the
666 // scope of that expression. This also guarantees basic WF.
667 let expr_ty = self.resolve_node_type(expr.id);
668 // the region corresponding to this expression
669 let expr_region = self.tcx.node_scope_region(expr.id);
670 self.type_must_outlive(infer::ExprTypeIsNotInScope(expr_ty, expr.span),
671 expr_ty, expr_region);
673 let is_method_call = self.tables.borrow().is_method_call(expr);
675 // If we are calling a method (either explicitly or via an
676 // overloaded operator), check that all of the types provided as
677 // arguments for its type parameters are well-formed, and all the regions
678 // provided as arguments outlive the call.
680 let origin = match expr.node {
681 hir::ExprMethodCall(..) =>
682 infer::ParameterOrigin::MethodCall,
683 hir::ExprUnary(op, _) if op == hir::UnDeref =>
684 infer::ParameterOrigin::OverloadedDeref,
686 infer::ParameterOrigin::OverloadedOperator
689 let substs = self.tables.borrow().node_substs(expr.id);
690 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
691 // Arguments (sub-expressions) are checked via `constrain_call`, below.
694 // Check any autoderefs or autorefs that appear.
695 let cmt_result = self.constrain_adjustments(expr);
697 // If necessary, constrain destructors in this expression. This will be
698 // the adjusted form if there is an adjustment.
701 self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, expr.span);
704 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
708 debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
709 expr, self.repeating_scope);
711 hir::ExprPath(_) => {
712 let substs = self.tables.borrow().node_substs(expr.id);
713 let origin = infer::ParameterOrigin::Path;
714 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
717 hir::ExprCall(ref callee, ref args) => {
719 self.constrain_call(expr, Some(&callee), args.iter().map(|e| &*e));
721 self.constrain_callee(callee.id, expr, &callee);
722 self.constrain_call(expr, None, args.iter().map(|e| &*e));
725 intravisit::walk_expr(self, expr);
728 hir::ExprMethodCall(.., ref args) => {
729 self.constrain_call(expr, Some(&args[0]), args[1..].iter().map(|e| &*e));
731 intravisit::walk_expr(self, expr);
734 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
736 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
739 intravisit::walk_expr(self, expr);
742 hir::ExprIndex(ref lhs, ref rhs) if is_method_call => {
743 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
745 intravisit::walk_expr(self, expr);
748 hir::ExprBinary(_, ref lhs, ref rhs) if is_method_call => {
749 // As `ExprMethodCall`, but the call is via an overloaded op.
750 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
752 intravisit::walk_expr(self, expr);
755 hir::ExprBinary(_, ref lhs, ref rhs) => {
756 // If you do `x OP y`, then the types of `x` and `y` must
757 // outlive the operation you are performing.
758 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
759 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
760 for &ty in &[lhs_ty, rhs_ty] {
761 self.type_must_outlive(infer::Operand(expr.span),
764 intravisit::walk_expr(self, expr);
767 hir::ExprUnary(hir::UnDeref, ref base) => {
768 // For *a, the lifetime of a must enclose the deref
770 self.constrain_call(expr, Some(base), None::<hir::Expr>.iter());
772 // For overloaded derefs, base_ty is the input to `Deref::deref`,
773 // but it's a reference type uing the same region as the output.
774 let base_ty = self.resolve_expr_type_adjusted(base);
775 if let ty::TyRef(r_ptr, _) = base_ty.sty {
776 self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
779 intravisit::walk_expr(self, expr);
782 hir::ExprUnary(_, ref lhs) if is_method_call => {
784 self.constrain_call(expr, Some(&lhs), None::<hir::Expr>.iter());
786 intravisit::walk_expr(self, expr);
789 hir::ExprIndex(ref vec_expr, _) => {
790 // For a[b], the lifetime of a must enclose the deref
791 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
792 self.constrain_index(expr, vec_type);
794 intravisit::walk_expr(self, expr);
797 hir::ExprCast(ref source, _) => {
798 // Determine if we are casting `source` to a trait
799 // instance. If so, we have to be sure that the type of
800 // the source obeys the trait's region bound.
801 self.constrain_cast(expr, &source);
802 intravisit::walk_expr(self, expr);
805 hir::ExprAddrOf(m, ref base) => {
806 self.link_addr_of(expr, m, &base);
808 // Require that when you write a `&expr` expression, the
809 // resulting pointer has a lifetime that encompasses the
810 // `&expr` expression itself. Note that we constraining
811 // the type of the node expr.id here *before applying
814 // FIXME(#6268) nested method calls requires that this rule change
815 let ty0 = self.resolve_node_type(expr.id);
816 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
817 intravisit::walk_expr(self, expr);
820 hir::ExprMatch(ref discr, ref arms, _) => {
821 self.link_match(&discr, &arms[..]);
823 intravisit::walk_expr(self, expr);
826 hir::ExprClosure(.., body_id, _) => {
827 self.check_expr_fn_block(expr, body_id);
830 hir::ExprLoop(ref body, _, _) => {
831 let repeating_scope = self.set_repeating_scope(body.id);
832 intravisit::walk_expr(self, expr);
833 self.set_repeating_scope(repeating_scope);
836 hir::ExprWhile(ref cond, ref body, _) => {
837 let repeating_scope = self.set_repeating_scope(cond.id);
838 self.visit_expr(&cond);
840 self.set_repeating_scope(body.id);
841 self.visit_block(&body);
843 self.set_repeating_scope(repeating_scope);
846 hir::ExprRet(Some(ref ret_expr)) => {
847 let call_site_scope = self.call_site_scope;
848 debug!("visit_expr ExprRet ret_expr.id {} call_site_scope: {:?}",
849 ret_expr.id, call_site_scope);
850 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
851 self.type_of_node_must_outlive(infer::CallReturn(ret_expr.span),
854 intravisit::walk_expr(self, expr);
858 intravisit::walk_expr(self, expr);
864 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
865 fn constrain_cast(&mut self,
866 cast_expr: &hir::Expr,
867 source_expr: &hir::Expr)
869 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
873 let source_ty = self.resolve_node_type(source_expr.id);
874 let target_ty = self.resolve_node_type(cast_expr.id);
876 self.walk_cast(cast_expr, source_ty, target_ty);
879 fn walk_cast(&mut self,
880 cast_expr: &hir::Expr,
883 debug!("walk_cast(from_ty={:?}, to_ty={:?})",
886 match (&from_ty.sty, &to_ty.sty) {
887 /*From:*/ (&ty::TyRef(from_r, ref from_mt),
888 /*To: */ &ty::TyRef(to_r, ref to_mt)) => {
889 // Target cannot outlive source, naturally.
890 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
891 self.walk_cast(cast_expr, from_mt.ty, to_mt.ty);
895 /*To: */ &ty::TyDynamic(.., r)) => {
896 // When T is existentially quantified as a trait
897 // `Foo+'to`, it must outlive the region bound `'to`.
898 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
901 /*From:*/ (&ty::TyAdt(from_def, _),
902 /*To: */ &ty::TyAdt(to_def, _)) if from_def.is_box() && to_def.is_box() => {
903 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
910 fn check_expr_fn_block(&mut self,
911 expr: &'gcx hir::Expr,
912 body_id: hir::BodyId) {
913 let repeating_scope = self.set_repeating_scope(body_id.node_id);
914 intravisit::walk_expr(self, expr);
915 self.set_repeating_scope(repeating_scope);
918 fn constrain_callee(&mut self,
919 callee_id: ast::NodeId,
920 _call_expr: &hir::Expr,
921 _callee_expr: &hir::Expr) {
922 let callee_ty = self.resolve_node_type(callee_id);
923 match callee_ty.sty {
924 ty::TyFnDef(..) | ty::TyFnPtr(_) => { }
926 // this should not happen, but it does if the program is
931 // "Calling non-function: {}",
937 fn constrain_call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
938 call_expr: &hir::Expr,
939 receiver: Option<&hir::Expr>,
941 //! Invoked on every call site (i.e., normal calls, method calls,
942 //! and overloaded operators). Constrains the regions which appear
943 //! in the type of the function. Also constrains the regions that
944 //! appear in the arguments appropriately.
946 debug!("constrain_call(call_expr={:?}, receiver={:?})",
950 // `callee_region` is the scope representing the time in which the
953 // FIXME(#6268) to support nested method calls, should be callee_id
954 let callee_scope = CodeExtent::Misc(call_expr.id);
955 let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
957 debug!("callee_region={:?}", callee_region);
959 for arg_expr in arg_exprs {
960 debug!("Argument: {:?}", arg_expr);
962 // ensure that any regions appearing in the argument type are
963 // valid for at least the lifetime of the function:
964 self.type_of_node_must_outlive(infer::CallArg(arg_expr.span),
965 arg_expr.id, callee_region);
968 // as loop above, but for receiver
969 if let Some(r) = receiver {
970 debug!("receiver: {:?}", r);
971 self.type_of_node_must_outlive(infer::CallRcvr(r.span),
972 r.id, callee_region);
976 /// Create a temporary `MemCategorizationContext` and pass it to the closure.
977 fn with_mc<F, R>(&self, f: F) -> R
978 where F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'gcx, 'tcx>) -> R
980 f(mc::MemCategorizationContext::with_infer(&self.infcx,
982 &self.tables.borrow()))
985 /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
986 /// dereferenced, the lifetime of the pointer includes the deref expr.
987 fn constrain_adjustments(&mut self, expr: &hir::Expr) -> mc::McResult<mc::cmt<'tcx>> {
988 debug!("constrain_adjustments(expr={:?})", expr);
990 let mut cmt = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
992 let tables = self.tables.borrow();
993 let adjustments = tables.expr_adjustments(&expr);
994 if adjustments.is_empty() {
998 debug!("constrain_adjustments: adjustments={:?}", adjustments);
1000 // If necessary, constrain destructors in the unadjusted form of this
1002 self.check_safety_of_rvalue_destructor_if_necessary(cmt.clone(), expr.span);
1004 let expr_region = self.tcx.node_scope_region(expr.id);
1005 for adjustment in adjustments {
1006 debug!("constrain_adjustments: adjustment={:?}, cmt={:?}",
1009 if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
1010 debug!("constrain_adjustments: overloaded deref: {:?}", deref);
1012 // Treat overloaded autoderefs as if an AutoBorrow adjustment
1013 // was applied on the base type, as that is always the case.
1014 let input = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
1018 let output = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
1019 ty: adjustment.target,
1023 self.link_region(expr.span, deref.region,
1024 ty::BorrowKind::from_mutbl(deref.mutbl), cmt.clone());
1026 // Specialized version of constrain_call.
1027 self.type_must_outlive(infer::CallRcvr(expr.span),
1028 input, expr_region);
1029 self.type_must_outlive(infer::CallReturn(expr.span),
1030 output, expr_region);
1033 if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
1034 self.link_autoref(expr, cmt.clone(), autoref);
1036 // Require that the resulting region encompasses
1037 // the current node.
1039 // FIXME(#6268) remove to support nested method calls
1040 self.type_of_node_must_outlive(infer::AutoBorrow(expr.span),
1041 expr.id, expr_region);
1044 cmt = self.with_mc(|mc| mc.cat_expr_adjusted(expr, cmt, &adjustment))?;
1046 if let Categorization::Deref(_, mc::BorrowedPtr(_, r_ptr)) = cmt.cat {
1047 self.mk_subregion_due_to_dereference(expr.span,
1048 expr_region, r_ptr);
1055 pub fn mk_subregion_due_to_dereference(&mut self,
1057 minimum_lifetime: ty::Region<'tcx>,
1058 maximum_lifetime: ty::Region<'tcx>) {
1059 self.sub_regions(infer::DerefPointer(deref_span),
1060 minimum_lifetime, maximum_lifetime)
1063 fn check_safety_of_rvalue_destructor_if_necessary(&mut self,
1067 Categorization::Rvalue(region) => {
1069 ty::ReScope(rvalue_scope) => {
1070 let typ = self.resolve_type(cmt.ty);
1071 let _ = dropck::check_safety_of_destructor_if_necessary(
1072 self, typ, span, rvalue_scope);
1077 "unexpected rvalue region in rvalue \
1078 destructor safety checking: `{:?}`",
1087 /// Invoked on any index expression that occurs. Checks that if this is a slice
1088 /// being indexed, the lifetime of the pointer includes the deref expr.
1089 fn constrain_index(&mut self,
1090 index_expr: &hir::Expr,
1091 indexed_ty: Ty<'tcx>)
1093 debug!("constrain_index(index_expr=?, indexed_ty={}",
1094 self.ty_to_string(indexed_ty));
1096 let r_index_expr = ty::ReScope(CodeExtent::Misc(index_expr.id));
1097 if let ty::TyRef(r_ptr, mt) = indexed_ty.sty {
1099 ty::TySlice(_) | ty::TyStr => {
1100 self.sub_regions(infer::IndexSlice(index_expr.span),
1101 self.tcx.mk_region(r_index_expr), r_ptr);
1108 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1109 /// adjustments) are valid for at least `minimum_lifetime`
1110 fn type_of_node_must_outlive(&mut self,
1111 origin: infer::SubregionOrigin<'tcx>,
1113 minimum_lifetime: ty::Region<'tcx>)
1115 // Try to resolve the type. If we encounter an error, then typeck
1116 // is going to fail anyway, so just stop here and let typeck
1117 // report errors later on in the writeback phase.
1118 let ty0 = self.resolve_node_type(id);
1119 let ty = self.tables.borrow().adjustments.get(&id)
1120 .and_then(|adj| adj.last())
1121 .map_or(ty0, |adj| adj.target);
1122 let ty = self.resolve_type(ty);
1123 debug!("constrain_regions_in_type_of_node(\
1124 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
1126 id, minimum_lifetime);
1127 self.type_must_outlive(origin, ty, minimum_lifetime);
1130 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1131 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1132 fn link_addr_of(&mut self, expr: &hir::Expr,
1133 mutability: hir::Mutability, base: &hir::Expr) {
1134 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
1136 let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
1138 debug!("link_addr_of: cmt={:?}", cmt);
1140 self.link_region_from_node_type(expr.span, expr.id, mutability, cmt);
1143 /// Computes the guarantors for any ref bindings in a `let` and
1144 /// then ensures that the lifetime of the resulting pointer is
1145 /// linked to the lifetime of the initialization expression.
1146 fn link_local(&self, local: &hir::Local) {
1147 debug!("regionck::for_local()");
1148 let init_expr = match local.init {
1150 Some(ref expr) => &**expr,
1152 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
1153 self.link_pattern(discr_cmt, &local.pat);
1156 /// Computes the guarantors for any ref bindings in a match and
1157 /// then ensures that the lifetime of the resulting pointer is
1158 /// linked to the lifetime of its guarantor (if any).
1159 fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) {
1160 debug!("regionck::for_match()");
1161 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
1162 debug!("discr_cmt={:?}", discr_cmt);
1164 for root_pat in &arm.pats {
1165 self.link_pattern(discr_cmt.clone(), &root_pat);
1170 /// Computes the guarantors for any ref bindings in a match and
1171 /// then ensures that the lifetime of the resulting pointer is
1172 /// linked to the lifetime of its guarantor (if any).
1173 fn link_fn_args(&self, body_scope: CodeExtent, args: &[hir::Arg]) {
1174 debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1176 let arg_ty = self.node_ty(arg.id);
1177 let re_scope = self.tcx.mk_region(ty::ReScope(body_scope));
1178 let arg_cmt = self.with_mc(|mc| {
1179 mc.cat_rvalue(arg.id, arg.pat.span, re_scope, arg_ty)
1181 debug!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1185 self.link_pattern(arg_cmt, &arg.pat);
1189 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1190 /// in the discriminant, if needed.
1191 fn link_pattern(&self, discr_cmt: mc::cmt<'tcx>, root_pat: &hir::Pat) {
1192 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1195 let _ = self.with_mc(|mc| {
1196 mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, sub_pat| {
1197 match sub_pat.node {
1199 PatKind::Binding(hir::BindByRef(mutbl), ..) => {
1200 self.link_region_from_node_type(sub_pat.span, sub_pat.id,
1209 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1211 fn link_autoref(&self,
1213 expr_cmt: mc::cmt<'tcx>,
1214 autoref: &adjustment::AutoBorrow<'tcx>)
1216 debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
1219 adjustment::AutoBorrow::Ref(r, m) => {
1220 self.link_region(expr.span, r,
1221 ty::BorrowKind::from_mutbl(m), expr_cmt);
1224 adjustment::AutoBorrow::RawPtr(m) => {
1225 let r = self.tcx.node_scope_region(expr.id);
1226 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1231 /// Like `link_region()`, except that the region is extracted from the type of `id`,
1232 /// which must be some reference (`&T`, `&str`, etc).
1233 fn link_region_from_node_type(&self,
1236 mutbl: hir::Mutability,
1237 cmt_borrowed: mc::cmt<'tcx>) {
1238 debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1239 id, mutbl, cmt_borrowed);
1241 let rptr_ty = self.resolve_node_type(id);
1242 if let ty::TyRef(r, _) = rptr_ty.sty {
1243 debug!("rptr_ty={}", rptr_ty);
1244 self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl),
1249 /// Informs the inference engine that `borrow_cmt` is being borrowed with
1250 /// kind `borrow_kind` and lifetime `borrow_region`.
1251 /// In order to ensure borrowck is satisfied, this may create constraints
1252 /// between regions, as explained in `link_reborrowed_region()`.
1253 fn link_region(&self,
1255 borrow_region: ty::Region<'tcx>,
1256 borrow_kind: ty::BorrowKind,
1257 borrow_cmt: mc::cmt<'tcx>) {
1258 let mut borrow_cmt = borrow_cmt;
1259 let mut borrow_kind = borrow_kind;
1261 let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1262 self.type_must_outlive(origin, borrow_cmt.ty, borrow_region);
1265 debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1269 match borrow_cmt.cat.clone() {
1270 Categorization::Deref(ref_cmt, mc::Implicit(ref_kind, ref_region)) |
1271 Categorization::Deref(ref_cmt, mc::BorrowedPtr(ref_kind, ref_region)) => {
1272 match self.link_reborrowed_region(span,
1273 borrow_region, borrow_kind,
1274 ref_cmt, ref_region, ref_kind,
1286 Categorization::Downcast(cmt_base, _) |
1287 Categorization::Deref(cmt_base, mc::Unique) |
1288 Categorization::Interior(cmt_base, _) => {
1289 // Borrowing interior or owned data requires the base
1290 // to be valid and borrowable in the same fashion.
1291 borrow_cmt = cmt_base;
1292 borrow_kind = borrow_kind;
1295 Categorization::Deref(_, mc::UnsafePtr(..)) |
1296 Categorization::StaticItem |
1297 Categorization::Upvar(..) |
1298 Categorization::Local(..) |
1299 Categorization::Rvalue(..) => {
1300 // These are all "base cases" with independent lifetimes
1301 // that are not subject to inference
1308 /// This is the most complicated case: the path being borrowed is
1309 /// itself the referent of a borrowed pointer. Let me give an
1310 /// example fragment of code to make clear(er) the situation:
1312 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1314 /// &'z *r // the reborrow has lifetime 'z
1316 /// Now, in this case, our primary job is to add the inference
1317 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1318 /// parameters in (roughly) terms of the example:
1320 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1321 /// borrow_region ^~ ref_region ^~
1322 /// borrow_kind ^~ ref_kind ^~
1325 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1327 /// Unfortunately, there are some complications beyond the simple
1328 /// scenario I just painted:
1330 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1331 /// case, we have two jobs. First, we are inferring whether this reference
1332 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1333 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1334 /// then `r` must be an `&mut` reference). Second, whenever we link
1335 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1336 /// case we adjust the cause to indicate that the reference being
1337 /// "reborrowed" is itself an upvar. This provides a nicer error message
1338 /// should something go wrong.
1340 /// 2. There may in fact be more levels of reborrowing. In the
1341 /// example, I said the borrow was like `&'z *r`, but it might
1342 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1343 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1344 /// and `'z <= 'b`. This is explained more below.
1346 /// The return value of this function indicates whether we need to
1347 /// recurse and process `ref_cmt` (see case 2 above).
1348 fn link_reborrowed_region(&self,
1350 borrow_region: ty::Region<'tcx>,
1351 borrow_kind: ty::BorrowKind,
1352 ref_cmt: mc::cmt<'tcx>,
1353 ref_region: ty::Region<'tcx>,
1354 mut ref_kind: ty::BorrowKind,
1356 -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1358 // Possible upvar ID we may need later to create an entry in the
1361 // Detect by-ref upvar `x`:
1362 let cause = match note {
1363 mc::NoteUpvarRef(ref upvar_id) => {
1364 match self.tables.borrow().upvar_capture_map.get(upvar_id) {
1365 Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1366 // The mutability of the upvar may have been modified
1367 // by the above adjustment, so update our local variable.
1368 ref_kind = upvar_borrow.kind;
1370 infer::ReborrowUpvar(span, *upvar_id)
1373 span_bug!( span, "Illegal upvar id: {:?}", upvar_id);
1377 mc::NoteClosureEnv(ref upvar_id) => {
1378 // We don't have any mutability changes to propagate, but
1379 // we do want to note that an upvar reborrow caused this
1381 infer::ReborrowUpvar(span, *upvar_id)
1384 infer::Reborrow(span)
1388 debug!("link_reborrowed_region: {:?} <= {:?}",
1391 self.sub_regions(cause, borrow_region, ref_region);
1393 // If we end up needing to recurse and establish a region link
1394 // with `ref_cmt`, calculate what borrow kind we will end up
1395 // needing. This will be used below.
1397 // One interesting twist is that we can weaken the borrow kind
1398 // when we recurse: to reborrow an `&mut` referent as mutable,
1399 // borrowck requires a unique path to the `&mut` reference but not
1400 // necessarily a *mutable* path.
1401 let new_borrow_kind = match borrow_kind {
1404 ty::MutBorrow | ty::UniqueImmBorrow =>
1408 // Decide whether we need to recurse and link any regions within
1409 // the `ref_cmt`. This is concerned for the case where the value
1410 // being reborrowed is in fact a borrowed pointer found within
1411 // another borrowed pointer. For example:
1413 // let p: &'b &'a mut T = ...;
1417 // What makes this case particularly tricky is that, if the data
1418 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1419 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1420 // (otherwise the user might mutate through the `&mut T` reference
1421 // after `'b` expires and invalidate the borrow we are looking at
1424 // So let's re-examine our parameters in light of this more
1425 // complicated (possible) scenario:
1427 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1428 // borrow_region ^~ ref_region ^~
1429 // borrow_kind ^~ ref_kind ^~
1432 // (Note that since we have not examined `ref_cmt.cat`, we don't
1433 // know whether this scenario has occurred; but I wanted to show
1434 // how all the types get adjusted.)
1437 // The reference being reborrowed is a sharable ref of
1438 // type `&'a T`. In this case, it doesn't matter where we
1439 // *found* the `&T` pointer, the memory it references will
1440 // be valid and immutable for `'a`. So we can stop here.
1442 // (Note that the `borrow_kind` must also be ImmBorrow or
1443 // else the user is borrowed imm memory as mut memory,
1444 // which means they'll get an error downstream in borrowck
1449 ty::MutBorrow | ty::UniqueImmBorrow => {
1450 // The reference being reborrowed is either an `&mut T` or
1451 // `&uniq T`. This is the case where recursion is needed.
1452 return Some((ref_cmt, new_borrow_kind));
1457 /// Checks that the values provided for type/region arguments in a given
1458 /// expression are well-formed and in-scope.
1459 fn substs_wf_in_scope(&mut self,
1460 origin: infer::ParameterOrigin,
1461 substs: &Substs<'tcx>,
1463 expr_region: ty::Region<'tcx>) {
1464 debug!("substs_wf_in_scope(substs={:?}, \
1468 substs, expr_region, origin, expr_span);
1470 let origin = infer::ParameterInScope(origin, expr_span);
1472 for region in substs.regions() {
1473 self.sub_regions(origin.clone(), expr_region, region);
1476 for ty in substs.types() {
1477 let ty = self.resolve_type(ty);
1478 self.type_must_outlive(origin.clone(), ty, expr_region);
1482 /// Ensures that type is well-formed in `region`, which implies (among
1483 /// other things) that all borrowed data reachable via `ty` outlives
1485 pub fn type_must_outlive(&self,
1486 origin: infer::SubregionOrigin<'tcx>,
1488 region: ty::Region<'tcx>)
1490 let ty = self.resolve_type(ty);
1492 debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})",
1497 assert!(!ty.has_escaping_regions());
1499 let components = self.tcx.outlives_components(ty);
1500 self.components_must_outlive(origin, components, region);
1503 fn components_must_outlive(&self,
1504 origin: infer::SubregionOrigin<'tcx>,
1505 components: Vec<Component<'tcx>>,
1506 region: ty::Region<'tcx>)
1508 for component in components {
1509 let origin = origin.clone();
1511 Component::Region(region1) => {
1512 self.sub_regions(origin, region, region1);
1514 Component::Param(param_ty) => {
1515 self.param_ty_must_outlive(origin, region, param_ty);
1517 Component::Projection(projection_ty) => {
1518 self.projection_must_outlive(origin, region, projection_ty);
1520 Component::EscapingProjection(subcomponents) => {
1521 self.components_must_outlive(origin, subcomponents, region);
1523 Component::UnresolvedInferenceVariable(v) => {
1524 // ignore this, we presume it will yield an error
1525 // later, since if a type variable is not resolved by
1526 // this point it never will be
1527 self.tcx.sess.delay_span_bug(
1529 &format!("unresolved inference variable in outlives: {:?}", v));
1535 fn param_ty_must_outlive(&self,
1536 origin: infer::SubregionOrigin<'tcx>,
1537 region: ty::Region<'tcx>,
1538 param_ty: ty::ParamTy) {
1539 debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1540 region, param_ty, origin);
1542 let verify_bound = self.param_bound(param_ty);
1543 let generic = GenericKind::Param(param_ty);
1544 self.verify_generic_bound(origin, generic, region, verify_bound);
1547 fn projection_must_outlive(&self,
1548 origin: infer::SubregionOrigin<'tcx>,
1549 region: ty::Region<'tcx>,
1550 projection_ty: ty::ProjectionTy<'tcx>)
1552 debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1553 region, projection_ty, origin);
1555 // This case is thorny for inference. The fundamental problem is
1556 // that there are many cases where we have choice, and inference
1557 // doesn't like choice (the current region inference in
1558 // particular). :) First off, we have to choose between using the
1559 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1560 // OutlivesProjectionComponent rules, any one of which is
1561 // sufficient. If there are no inference variables involved, it's
1562 // not hard to pick the right rule, but if there are, we're in a
1563 // bit of a catch 22: if we picked which rule we were going to
1564 // use, we could add constraints to the region inference graph
1565 // that make it apply, but if we don't add those constraints, the
1566 // rule might not apply (but another rule might). For now, we err
1567 // on the side of adding too few edges into the graph.
1569 // Compute the bounds we can derive from the environment or trait
1570 // definition. We know that the projection outlives all the
1571 // regions in this list.
1572 let env_bounds = self.projection_declared_bounds(origin.span(), projection_ty);
1574 debug!("projection_must_outlive: env_bounds={:?}",
1577 // If we know that the projection outlives 'static, then we're
1579 if env_bounds.contains(&&ty::ReStatic) {
1580 debug!("projection_must_outlive: 'static as declared bound");
1584 // If declared bounds list is empty, the only applicable rule is
1585 // OutlivesProjectionComponent. If there are inference variables,
1586 // then, we can break down the outlives into more primitive
1587 // components without adding unnecessary edges.
1589 // If there are *no* inference variables, however, we COULD do
1590 // this, but we choose not to, because the error messages are less
1591 // good. For example, a requirement like `T::Item: 'r` would be
1592 // translated to a requirement that `T: 'r`; when this is reported
1593 // to the user, it will thus say "T: 'r must hold so that T::Item:
1594 // 'r holds". But that makes it sound like the only way to fix
1595 // the problem is to add `T: 'r`, which isn't true. So, if there are no
1596 // inference variables, we use a verify constraint instead of adding
1597 // edges, which winds up enforcing the same condition.
1598 let needs_infer = projection_ty.needs_infer();
1599 if env_bounds.is_empty() && needs_infer {
1600 debug!("projection_must_outlive: no declared bounds");
1602 for component_ty in projection_ty.substs.types() {
1603 self.type_must_outlive(origin.clone(), component_ty, region);
1606 for r in projection_ty.substs.regions() {
1607 self.sub_regions(origin.clone(), region, r);
1613 // If we find that there is a unique declared bound `'b`, and this bound
1614 // appears in the trait reference, then the best action is to require that `'b:'r`,
1615 // so do that. This is best no matter what rule we use:
1617 // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1618 // the requirement that `'b:'r`
1619 // - OutlivesProjectionComponent: this would require `'b:'r` in addition to
1621 if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) {
1622 let unique_bound = env_bounds[0];
1623 debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound);
1624 if projection_ty.substs.regions().any(|r| env_bounds.contains(&r)) {
1625 debug!("projection_must_outlive: unique declared bound appears in trait ref");
1626 self.sub_regions(origin.clone(), region, unique_bound);
1631 // Fallback to verifying after the fact that there exists a
1632 // declared bound, or that all the components appearing in the
1633 // projection outlive; in some cases, this may add insufficient
1634 // edges into the inference graph, leading to inference failures
1635 // even though a satisfactory solution exists.
1636 let verify_bound = self.projection_bound(origin.span(), env_bounds, projection_ty);
1637 let generic = GenericKind::Projection(projection_ty);
1638 self.verify_generic_bound(origin, generic.clone(), region, verify_bound);
1641 fn type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1646 ty::TyProjection(data) => {
1647 let declared_bounds = self.projection_declared_bounds(span, data);
1648 self.projection_bound(span, declared_bounds, data)
1651 self.recursive_type_bound(span, ty)
1656 fn param_bound(&self, param_ty: ty::ParamTy) -> VerifyBound<'tcx> {
1657 debug!("param_bound(param_ty={:?})",
1660 let mut param_bounds = self.declared_generic_bounds_from_env(GenericKind::Param(param_ty));
1662 // Add in the default bound of fn body that applies to all in
1663 // scope type parameters:
1664 param_bounds.extend(self.implicit_region_bound);
1666 VerifyBound::AnyRegion(param_bounds)
1669 fn projection_declared_bounds(&self,
1671 projection_ty: ty::ProjectionTy<'tcx>)
1672 -> Vec<ty::Region<'tcx>>
1674 // First assemble bounds from where clauses and traits.
1676 let mut declared_bounds =
1677 self.declared_generic_bounds_from_env(GenericKind::Projection(projection_ty));
1679 declared_bounds.extend_from_slice(
1680 &self.declared_projection_bounds_from_trait(span, projection_ty));
1685 fn projection_bound(&self,
1687 declared_bounds: Vec<ty::Region<'tcx>>,
1688 projection_ty: ty::ProjectionTy<'tcx>)
1689 -> VerifyBound<'tcx> {
1690 debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1691 declared_bounds, projection_ty);
1693 // see the extensive comment in projection_must_outlive
1694 let ty = self.tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs);
1695 let recursive_bound = self.recursive_type_bound(span, ty);
1697 VerifyBound::AnyRegion(declared_bounds).or(recursive_bound)
1700 fn recursive_type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1701 let mut bounds = vec![];
1703 for subty in ty.walk_shallow() {
1704 bounds.push(self.type_bound(span, subty));
1707 let mut regions = ty.regions();
1708 regions.retain(|r| !r.is_late_bound()); // ignore late-bound regions
1709 bounds.push(VerifyBound::AllRegions(regions));
1711 // remove bounds that must hold, since they are not interesting
1712 bounds.retain(|b| !b.must_hold());
1714 if bounds.len() == 1 {
1715 bounds.pop().unwrap()
1717 VerifyBound::AllBounds(bounds)
1721 fn declared_generic_bounds_from_env(&self, generic: GenericKind<'tcx>)
1722 -> Vec<ty::Region<'tcx>>
1724 let param_env = &self.param_env;
1726 // To start, collect bounds from user:
1727 let mut param_bounds = self.tcx.required_region_bounds(generic.to_ty(self.tcx),
1728 param_env.caller_bounds.to_vec());
1730 // Next, collect regions we scraped from the well-formedness
1731 // constraints in the fn signature. To do that, we walk the list
1732 // of known relations from the fn ctxt.
1734 // This is crucial because otherwise code like this fails:
1736 // fn foo<'a, A>(x: &'a A) { x.bar() }
1738 // The problem is that the type of `x` is `&'a A`. To be
1739 // well-formed, then, A must be lower-generic by `'a`, but we
1740 // don't know that this holds from first principles.
1741 for &(r, p) in &self.region_bound_pairs {
1742 debug!("generic={:?} p={:?}",
1746 param_bounds.push(r);
1753 fn declared_projection_bounds_from_trait(&self,
1755 projection_ty: ty::ProjectionTy<'tcx>)
1756 -> Vec<ty::Region<'tcx>>
1758 debug!("projection_bounds(projection_ty={:?})",
1760 let ty = self.tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs);
1762 // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1763 // in looking for a trait definition like:
1766 // trait SomeTrait<'a> {
1767 // type SomeType : 'a;
1771 // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1772 let trait_predicates = self.tcx.predicates_of(projection_ty.trait_ref(self.tcx).def_id);
1773 assert_eq!(trait_predicates.parent, None);
1774 let predicates = trait_predicates.predicates.as_slice().to_vec();
1775 traits::elaborate_predicates(self.tcx, predicates)
1776 .filter_map(|predicate| {
1777 // we're only interesting in `T : 'a` style predicates:
1778 let outlives = match predicate {
1779 ty::Predicate::TypeOutlives(data) => data,
1780 _ => { return None; }
1783 debug!("projection_bounds: outlives={:?} (1)",
1786 // apply the substitutions (and normalize any projected types)
1787 let outlives = self.instantiate_type_scheme(span,
1788 projection_ty.substs,
1791 debug!("projection_bounds: outlives={:?} (2)",
1794 let region_result = self.commit_if_ok(|_| {
1796 self.replace_late_bound_regions_with_fresh_var(
1798 infer::AssocTypeProjection(
1799 self.tcx.associated_item(projection_ty.item_def_id).name),
1802 debug!("projection_bounds: outlives={:?} (3)",
1805 // check whether this predicate applies to our current projection
1806 let cause = self.fcx.misc(span);
1807 match self.at(&cause, self.fcx.param_env).eq(outlives.0, ty) {
1809 self.register_infer_ok_obligations(ok);
1812 Err(_) => { Err(()) }
1816 debug!("projection_bounds: region_result={:?}",