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;
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_scope_tree: Rc<region::ScopeTree>,
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<region::Scope>,
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_scope_tree = fcx.tcx.region_scope_tree(subject);
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<region::Scope>)
247 -> Option<region::Scope> {
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: hir::HirId) -> 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 = region::Scope::CallSite(body.value.hir_id.local_id);
309 let old_call_site_scope = self.set_call_site_scope(Some(call_site));
312 let fn_hir_id = self.tcx.hir.node_to_hir_id(id);
313 match self.tables.borrow().liberated_fn_sigs().get(fn_hir_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(region::Scope::Node(body.value.hir_id.local_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 let body_hir_id = self.tcx.hir.node_to_hir_id(body_id.node_id);
342 self.type_of_node_must_outlive(infer::CallReturn(span),
346 self.region_bound_pairs.truncate(old_region_bounds_pairs_len);
348 self.set_body_id(old_body_id);
349 self.set_call_site_scope(old_call_site_scope);
352 fn visit_region_obligations(&mut self, node_id: ast::NodeId)
354 debug!("visit_region_obligations: node_id={}", node_id);
356 // region checking can introduce new pending obligations
357 // which, when processed, might generate new region
358 // obligations. So make sure we process those.
359 self.select_all_obligations_or_error();
361 // Make a copy of the region obligations vec because we'll need
362 // to be able to borrow the fulfillment-cx below when projecting.
363 let region_obligations =
366 .region_obligations(node_id)
369 for r_o in ®ion_obligations {
370 debug!("visit_region_obligations: r_o={:?} cause={:?}",
372 let sup_type = self.resolve_type(r_o.sup_type);
373 let origin = self.code_to_origin(&r_o.cause, sup_type);
374 self.type_must_outlive(origin, sup_type, r_o.sub_region);
377 // Processing the region obligations should not cause the list to grow further:
378 assert_eq!(region_obligations.len(),
379 self.fulfillment_cx.borrow().region_obligations(node_id).len());
382 fn code_to_origin(&self,
383 cause: &traits::ObligationCause<'tcx>,
385 -> SubregionOrigin<'tcx> {
386 SubregionOrigin::from_obligation_cause(cause,
387 || infer::RelateParamBound(cause.span, sup_type))
390 /// This method populates the region map's `free_region_map`. It walks over the transformed
391 /// argument and return types for each function just before we check the body of that function,
392 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
393 /// [usize]`. We do not allow references to outlive the things they point at, so we can assume
394 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
395 /// the caller side, the caller is responsible for checking that the type of every expression
396 /// (including the actual values for the arguments, as well as the return type of the fn call)
399 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
400 fn relate_free_regions(&mut self,
401 fn_sig_tys: &[Ty<'tcx>],
402 body_id: ast::NodeId,
404 debug!("relate_free_regions >>");
406 for &ty in fn_sig_tys {
407 let ty = self.resolve_type(ty);
408 debug!("relate_free_regions(t={:?})", ty);
409 let implied_bounds = self.implied_bounds(body_id, ty, span);
411 // But also record other relationships, such as `T:'x`,
412 // that don't go into the free-region-map but which we use
414 for implication in implied_bounds {
415 debug!("implication: {:?}", implication);
417 ImpliedBound::RegionSubRegion(r_a @ &ty::ReEarlyBound(_),
419 ImpliedBound::RegionSubRegion(r_a @ &ty::ReFree(_),
420 &ty::ReVar(vid_b)) => {
421 self.add_given(r_a, vid_b);
423 ImpliedBound::RegionSubParam(r_a, param_b) => {
424 self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
426 ImpliedBound::RegionSubProjection(r_a, projection_b) => {
427 self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
429 ImpliedBound::RegionSubRegion(r_a, r_b) => {
430 // In principle, we could record (and take
431 // advantage of) every relationship here, but
432 // we are also free not to -- it simply means
433 // strictly less that we can successfully type
434 // check. Right now we only look for things
435 // relationships between free regions. (It may
436 // also be that we should revise our inference
437 // system to be more general and to make use
438 // of *every* relationship that arises here,
439 // but presently we do not.)
440 self.free_region_map.relate_regions(r_a, r_b);
446 debug!("<< relate_free_regions");
449 /// Compute the implied bounds that a callee/impl can assume based on
450 /// the fact that caller/projector has ensured that `ty` is WF. See
451 /// the `ImpliedBound` type for more details.
452 fn implied_bounds(&mut self, body_id: ast::NodeId, ty: Ty<'tcx>, span: Span)
453 -> Vec<ImpliedBound<'tcx>> {
454 // Sometimes when we ask what it takes for T: WF, we get back that
455 // U: WF is required; in that case, we push U onto this stack and
456 // process it next. Currently (at least) these resulting
457 // predicates are always guaranteed to be a subset of the original
458 // type, so we need not fear non-termination.
459 let mut wf_types = vec![ty];
461 let mut implied_bounds = vec![];
463 while let Some(ty) = wf_types.pop() {
464 // Compute the obligations for `ty` to be well-formed. If `ty` is
465 // an unresolved inference variable, just substituted an empty set
466 // -- because the return type here is going to be things we *add*
467 // to the environment, it's always ok for this set to be smaller
468 // than the ultimate set. (Note: normally there won't be
469 // unresolved inference variables here anyway, but there might be
470 // during typeck under some circumstances.)
472 wf::obligations(self, self.fcx.param_env, body_id, ty, span)
475 // NB: All of these predicates *ought* to be easily proven
476 // true. In fact, their correctness is (mostly) implied by
477 // other parts of the program. However, in #42552, we had
478 // an annoying scenario where:
480 // - Some `T::Foo` gets normalized, resulting in a
481 // variable `_1` and a `T: Trait<Foo=_1>` constraint
482 // (not sure why it couldn't immediately get
483 // solved). This result of `_1` got cached.
484 // - These obligations were dropped on the floor here,
485 // rather than being registered.
486 // - Then later we would get a request to normalize
487 // `T::Foo` which would result in `_1` being used from
488 // the cache, but hence without the `T: Trait<Foo=_1>`
489 // constraint. As a result, `_1` never gets resolved,
490 // and we get an ICE (in dropck).
492 // Therefore, we register any predicates involving
493 // inference variables. We restrict ourselves to those
494 // involving inference variables both for efficiency and
495 // to avoids duplicate errors that otherwise show up.
496 self.fcx.register_predicates(
498 .filter(|o| o.predicate.has_infer_types())
501 // From the full set of obligations, just filter down to the
502 // region relationships.
503 implied_bounds.extend(
506 .flat_map(|obligation| {
507 assert!(!obligation.has_escaping_regions());
508 match obligation.predicate {
509 ty::Predicate::Trait(..) |
510 ty::Predicate::Equate(..) |
511 ty::Predicate::Subtype(..) |
512 ty::Predicate::Projection(..) |
513 ty::Predicate::ClosureKind(..) |
514 ty::Predicate::ObjectSafe(..) |
515 ty::Predicate::ConstEvaluatable(..) =>
518 ty::Predicate::WellFormed(subty) => {
519 wf_types.push(subty);
523 ty::Predicate::RegionOutlives(ref data) =>
524 match self.tcx.no_late_bound_regions(data) {
527 Some(ty::OutlivesPredicate(r_a, r_b)) =>
528 vec![ImpliedBound::RegionSubRegion(r_b, r_a)],
531 ty::Predicate::TypeOutlives(ref data) =>
532 match self.tcx.no_late_bound_regions(data) {
534 Some(ty::OutlivesPredicate(ty_a, r_b)) => {
535 let ty_a = self.resolve_type_vars_if_possible(&ty_a);
536 let components = self.tcx.outlives_components(ty_a);
537 self.implied_bounds_from_components(r_b, components)
546 /// When we have an implied bound that `T: 'a`, we can further break
547 /// this down to determine what relationships would have to hold for
548 /// `T: 'a` to hold. We get to assume that the caller has validated
549 /// those relationships.
550 fn implied_bounds_from_components(&self,
551 sub_region: ty::Region<'tcx>,
552 sup_components: Vec<Component<'tcx>>)
553 -> Vec<ImpliedBound<'tcx>>
557 .flat_map(|component| {
559 Component::Region(r) =>
560 vec![ImpliedBound::RegionSubRegion(sub_region, r)],
561 Component::Param(p) =>
562 vec![ImpliedBound::RegionSubParam(sub_region, p)],
563 Component::Projection(p) =>
564 vec![ImpliedBound::RegionSubProjection(sub_region, p)],
565 Component::EscapingProjection(_) =>
566 // If the projection has escaping regions, don't
567 // try to infer any implied bounds even for its
568 // free components. This is conservative, because
569 // the caller will still have to prove that those
570 // free components outlive `sub_region`. But the
571 // idea is that the WAY that the caller proves
572 // that may change in the future and we want to
573 // give ourselves room to get smarter here.
575 Component::UnresolvedInferenceVariable(..) =>
582 fn resolve_regions_and_report_errors(&self) {
583 self.fcx.resolve_regions_and_report_errors(self.subject_def_id,
584 &self.region_scope_tree,
585 &self.free_region_map);
588 fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) {
589 debug!("regionck::visit_pat(pat={:?})", pat);
590 pat.each_binding(|_, id, span, _| {
591 // If we have a variable that contains region'd data, that
592 // data will be accessible from anywhere that the variable is
593 // accessed. We must be wary of loops like this:
595 // // from src/test/compile-fail/borrowck-lend-flow.rs
596 // let mut v = box 3, w = box 4;
597 // let mut x = &mut w;
600 // borrow(v); //~ ERROR cannot borrow
601 // x = &mut v; // (1)
604 // Typically, we try to determine the region of a borrow from
605 // those points where it is dereferenced. In this case, one
606 // might imagine that the lifetime of `x` need only be the
607 // body of the loop. But of course this is incorrect because
608 // the pointer that is created at point (1) is consumed at
609 // point (2), meaning that it must be live across the loop
610 // iteration. The easiest way to guarantee this is to require
611 // that the lifetime of any regions that appear in a
612 // variable's type enclose at least the variable's scope.
614 let hir_id = self.tcx.hir.node_to_hir_id(id);
615 let var_scope = self.region_scope_tree.var_scope(hir_id.local_id);
616 let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
618 let origin = infer::BindingTypeIsNotValidAtDecl(span);
619 self.type_of_node_must_outlive(origin, hir_id, var_region);
621 let typ = self.resolve_node_type(hir_id);
622 let _ = dropck::check_safety_of_destructor_if_necessary(
623 self, typ, span, var_scope);
628 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for RegionCtxt<'a, 'gcx, 'tcx> {
629 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
630 // However, right now we run into an issue whereby some free
631 // regions are not properly related if they appear within the
632 // types of arguments that must be inferred. This could be
633 // addressed by deferring the construction of the region
634 // hierarchy, and in particular the relationships between free
635 // regions, until regionck, as described in #3238.
637 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
638 NestedVisitorMap::None
641 fn visit_fn(&mut self, _fk: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
642 b: hir::BodyId, span: Span, id: ast::NodeId) {
643 let body = self.tcx.hir.body(b);
644 self.visit_fn_body(id, body, span)
647 //visit_pat: visit_pat, // (..) see above
649 fn visit_arm(&mut self, arm: &'gcx hir::Arm) {
652 self.constrain_bindings_in_pat(p);
654 intravisit::walk_arm(self, arm);
657 fn visit_local(&mut self, l: &'gcx hir::Local) {
659 self.constrain_bindings_in_pat(&l.pat);
661 intravisit::walk_local(self, l);
664 fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
665 debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
666 expr, self.repeating_scope);
668 // No matter what, the type of each expression must outlive the
669 // scope of that expression. This also guarantees basic WF.
670 let expr_ty = self.resolve_node_type(expr.hir_id);
671 // the region corresponding to this expression
672 let expr_region = self.tcx.mk_region(ty::ReScope(
673 region::Scope::Node(expr.hir_id.local_id)));
674 self.type_must_outlive(infer::ExprTypeIsNotInScope(expr_ty, expr.span),
675 expr_ty, expr_region);
677 let is_method_call = self.tables.borrow().is_method_call(expr);
679 // If we are calling a method (either explicitly or via an
680 // overloaded operator), check that all of the types provided as
681 // arguments for its type parameters are well-formed, and all the regions
682 // provided as arguments outlive the call.
684 let origin = match expr.node {
685 hir::ExprMethodCall(..) =>
686 infer::ParameterOrigin::MethodCall,
687 hir::ExprUnary(op, _) if op == hir::UnDeref =>
688 infer::ParameterOrigin::OverloadedDeref,
690 infer::ParameterOrigin::OverloadedOperator
693 let substs = self.tables.borrow().node_substs(expr.hir_id);
694 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
695 // Arguments (sub-expressions) are checked via `constrain_call`, below.
698 // Check any autoderefs or autorefs that appear.
699 let cmt_result = self.constrain_adjustments(expr);
701 // If necessary, constrain destructors in this expression. This will be
702 // the adjusted form if there is an adjustment.
705 self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, expr.span);
708 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
712 debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
713 expr, self.repeating_scope);
715 hir::ExprPath(_) => {
716 let substs = self.tables.borrow().node_substs(expr.hir_id);
717 let origin = infer::ParameterOrigin::Path;
718 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
721 hir::ExprCall(ref callee, ref args) => {
723 self.constrain_call(expr, Some(&callee), args.iter().map(|e| &*e));
725 self.constrain_callee(&callee);
726 self.constrain_call(expr, None, args.iter().map(|e| &*e));
729 intravisit::walk_expr(self, expr);
732 hir::ExprMethodCall(.., ref args) => {
733 self.constrain_call(expr, Some(&args[0]), args[1..].iter().map(|e| &*e));
735 intravisit::walk_expr(self, expr);
738 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
740 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
743 intravisit::walk_expr(self, expr);
746 hir::ExprIndex(ref lhs, ref rhs) if is_method_call => {
747 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
749 intravisit::walk_expr(self, expr);
752 hir::ExprBinary(_, ref lhs, ref rhs) if is_method_call => {
753 // As `ExprMethodCall`, but the call is via an overloaded op.
754 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
756 intravisit::walk_expr(self, expr);
759 hir::ExprBinary(_, ref lhs, ref rhs) => {
760 // If you do `x OP y`, then the types of `x` and `y` must
761 // outlive the operation you are performing.
762 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
763 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
764 for &ty in &[lhs_ty, rhs_ty] {
765 self.type_must_outlive(infer::Operand(expr.span),
768 intravisit::walk_expr(self, expr);
771 hir::ExprUnary(hir::UnDeref, ref base) => {
772 // For *a, the lifetime of a must enclose the deref
774 self.constrain_call(expr, Some(base), None::<hir::Expr>.iter());
776 // For overloaded derefs, base_ty is the input to `Deref::deref`,
777 // but it's a reference type uing the same region as the output.
778 let base_ty = self.resolve_expr_type_adjusted(base);
779 if let ty::TyRef(r_ptr, _) = base_ty.sty {
780 self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
783 intravisit::walk_expr(self, expr);
786 hir::ExprUnary(_, ref lhs) if is_method_call => {
788 self.constrain_call(expr, Some(&lhs), None::<hir::Expr>.iter());
790 intravisit::walk_expr(self, expr);
793 hir::ExprIndex(ref vec_expr, _) => {
794 // For a[b], the lifetime of a must enclose the deref
795 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
796 self.constrain_index(expr, vec_type);
798 intravisit::walk_expr(self, expr);
801 hir::ExprCast(ref source, _) => {
802 // Determine if we are casting `source` to a trait
803 // instance. If so, we have to be sure that the type of
804 // the source obeys the trait's region bound.
805 self.constrain_cast(expr, &source);
806 intravisit::walk_expr(self, expr);
809 hir::ExprAddrOf(m, ref base) => {
810 self.link_addr_of(expr, m, &base);
812 // Require that when you write a `&expr` expression, the
813 // resulting pointer has a lifetime that encompasses the
814 // `&expr` expression itself. Note that we constraining
815 // the type of the node expr.id here *before applying
818 // FIXME(#6268) nested method calls requires that this rule change
819 let ty0 = self.resolve_node_type(expr.hir_id);
820 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
821 intravisit::walk_expr(self, expr);
824 hir::ExprMatch(ref discr, ref arms, _) => {
825 self.link_match(&discr, &arms[..]);
827 intravisit::walk_expr(self, expr);
830 hir::ExprClosure(.., body_id, _, _) => {
831 self.check_expr_fn_block(expr, body_id);
834 hir::ExprLoop(ref body, _, _) => {
835 let repeating_scope = self.set_repeating_scope(body.id);
836 intravisit::walk_expr(self, expr);
837 self.set_repeating_scope(repeating_scope);
840 hir::ExprWhile(ref cond, ref body, _) => {
841 let repeating_scope = self.set_repeating_scope(cond.id);
842 self.visit_expr(&cond);
844 self.set_repeating_scope(body.id);
845 self.visit_block(&body);
847 self.set_repeating_scope(repeating_scope);
850 hir::ExprRet(Some(ref ret_expr)) => {
851 let call_site_scope = self.call_site_scope;
852 debug!("visit_expr ExprRet ret_expr.id {} call_site_scope: {:?}",
853 ret_expr.id, call_site_scope);
854 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
855 self.type_of_node_must_outlive(infer::CallReturn(ret_expr.span),
858 intravisit::walk_expr(self, expr);
862 intravisit::walk_expr(self, expr);
868 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
869 fn constrain_cast(&mut self,
870 cast_expr: &hir::Expr,
871 source_expr: &hir::Expr)
873 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
877 let source_ty = self.resolve_node_type(source_expr.hir_id);
878 let target_ty = self.resolve_node_type(cast_expr.hir_id);
880 self.walk_cast(cast_expr, source_ty, target_ty);
883 fn walk_cast(&mut self,
884 cast_expr: &hir::Expr,
887 debug!("walk_cast(from_ty={:?}, to_ty={:?})",
890 match (&from_ty.sty, &to_ty.sty) {
891 /*From:*/ (&ty::TyRef(from_r, ref from_mt),
892 /*To: */ &ty::TyRef(to_r, ref to_mt)) => {
893 // Target cannot outlive source, naturally.
894 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
895 self.walk_cast(cast_expr, from_mt.ty, to_mt.ty);
899 /*To: */ &ty::TyDynamic(.., r)) => {
900 // When T is existentially quantified as a trait
901 // `Foo+'to`, it must outlive the region bound `'to`.
902 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
905 /*From:*/ (&ty::TyAdt(from_def, _),
906 /*To: */ &ty::TyAdt(to_def, _)) if from_def.is_box() && to_def.is_box() => {
907 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
914 fn check_expr_fn_block(&mut self,
915 expr: &'gcx hir::Expr,
916 body_id: hir::BodyId) {
917 let repeating_scope = self.set_repeating_scope(body_id.node_id);
918 intravisit::walk_expr(self, expr);
919 self.set_repeating_scope(repeating_scope);
922 fn constrain_callee(&mut self, callee_expr: &hir::Expr) {
923 let callee_ty = self.resolve_node_type(callee_expr.hir_id);
924 match callee_ty.sty {
925 ty::TyFnDef(..) | ty::TyFnPtr(_) => { }
927 // this should not happen, but it does if the program is
932 // "Calling non-function: {}",
938 fn constrain_call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
939 call_expr: &hir::Expr,
940 receiver: Option<&hir::Expr>,
942 //! Invoked on every call site (i.e., normal calls, method calls,
943 //! and overloaded operators). Constrains the regions which appear
944 //! in the type of the function. Also constrains the regions that
945 //! appear in the arguments appropriately.
947 debug!("constrain_call(call_expr={:?}, receiver={:?})",
951 // `callee_region` is the scope representing the time in which the
954 // FIXME(#6268) to support nested method calls, should be callee_id
955 let callee_scope = region::Scope::Node(call_expr.hir_id.local_id);
956 let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
958 debug!("callee_region={:?}", callee_region);
960 for arg_expr in arg_exprs {
961 debug!("Argument: {:?}", arg_expr);
963 // ensure that any regions appearing in the argument type are
964 // valid for at least the lifetime of the function:
965 self.type_of_node_must_outlive(infer::CallArg(arg_expr.span),
970 // as loop above, but for receiver
971 if let Some(r) = receiver {
972 debug!("receiver: {:?}", r);
973 self.type_of_node_must_outlive(infer::CallRcvr(r.span),
979 /// Create a temporary `MemCategorizationContext` and pass it to the closure.
980 fn with_mc<F, R>(&self, f: F) -> R
981 where F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'gcx, 'tcx>) -> R
983 f(mc::MemCategorizationContext::with_infer(&self.infcx,
984 &self.region_scope_tree,
985 &self.tables.borrow()))
988 /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
989 /// dereferenced, the lifetime of the pointer includes the deref expr.
990 fn constrain_adjustments(&mut self, expr: &hir::Expr) -> mc::McResult<mc::cmt<'tcx>> {
991 debug!("constrain_adjustments(expr={:?})", expr);
993 let mut cmt = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
995 let tables = self.tables.borrow();
996 let adjustments = tables.expr_adjustments(&expr);
997 if adjustments.is_empty() {
1001 debug!("constrain_adjustments: adjustments={:?}", adjustments);
1003 // If necessary, constrain destructors in the unadjusted form of this
1005 self.check_safety_of_rvalue_destructor_if_necessary(cmt.clone(), expr.span);
1007 let expr_region = self.tcx.mk_region(ty::ReScope(
1008 region::Scope::Node(expr.hir_id.local_id)));
1009 for adjustment in adjustments {
1010 debug!("constrain_adjustments: adjustment={:?}, cmt={:?}",
1013 if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
1014 debug!("constrain_adjustments: overloaded deref: {:?}", deref);
1016 // Treat overloaded autoderefs as if an AutoBorrow adjustment
1017 // was applied on the base type, as that is always the case.
1018 let input = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
1022 let output = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
1023 ty: adjustment.target,
1027 self.link_region(expr.span, deref.region,
1028 ty::BorrowKind::from_mutbl(deref.mutbl), cmt.clone());
1030 // Specialized version of constrain_call.
1031 self.type_must_outlive(infer::CallRcvr(expr.span),
1032 input, expr_region);
1033 self.type_must_outlive(infer::CallReturn(expr.span),
1034 output, expr_region);
1037 if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
1038 self.link_autoref(expr, cmt.clone(), autoref);
1040 // Require that the resulting region encompasses
1041 // the current node.
1043 // FIXME(#6268) remove to support nested method calls
1044 self.type_of_node_must_outlive(infer::AutoBorrow(expr.span),
1049 cmt = self.with_mc(|mc| mc.cat_expr_adjusted(expr, cmt, &adjustment))?;
1051 if let Categorization::Deref(_, mc::BorrowedPtr(_, r_ptr)) = cmt.cat {
1052 self.mk_subregion_due_to_dereference(expr.span,
1053 expr_region, r_ptr);
1060 pub fn mk_subregion_due_to_dereference(&mut self,
1062 minimum_lifetime: ty::Region<'tcx>,
1063 maximum_lifetime: ty::Region<'tcx>) {
1064 self.sub_regions(infer::DerefPointer(deref_span),
1065 minimum_lifetime, maximum_lifetime)
1068 fn check_safety_of_rvalue_destructor_if_necessary(&mut self,
1072 Categorization::Rvalue(region) => {
1074 ty::ReScope(rvalue_scope) => {
1075 let typ = self.resolve_type(cmt.ty);
1076 let _ = dropck::check_safety_of_destructor_if_necessary(
1077 self, typ, span, rvalue_scope);
1082 "unexpected rvalue region in rvalue \
1083 destructor safety checking: `{:?}`",
1092 /// Invoked on any index expression that occurs. Checks that if this is a slice
1093 /// being indexed, the lifetime of the pointer includes the deref expr.
1094 fn constrain_index(&mut self,
1095 index_expr: &hir::Expr,
1096 indexed_ty: Ty<'tcx>)
1098 debug!("constrain_index(index_expr=?, indexed_ty={}",
1099 self.ty_to_string(indexed_ty));
1101 let r_index_expr = ty::ReScope(region::Scope::Node(index_expr.hir_id.local_id));
1102 if let ty::TyRef(r_ptr, mt) = indexed_ty.sty {
1104 ty::TySlice(_) | ty::TyStr => {
1105 self.sub_regions(infer::IndexSlice(index_expr.span),
1106 self.tcx.mk_region(r_index_expr), r_ptr);
1113 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1114 /// adjustments) are valid for at least `minimum_lifetime`
1115 fn type_of_node_must_outlive(&mut self,
1116 origin: infer::SubregionOrigin<'tcx>,
1118 minimum_lifetime: ty::Region<'tcx>)
1120 // Try to resolve the type. If we encounter an error, then typeck
1121 // is going to fail anyway, so just stop here and let typeck
1122 // report errors later on in the writeback phase.
1123 let ty0 = self.resolve_node_type(hir_id);
1125 let ty = self.tables
1129 .and_then(|adj| adj.last())
1130 .map_or(ty0, |adj| adj.target);
1131 let ty = self.resolve_type(ty);
1132 debug!("constrain_regions_in_type_of_node(\
1133 ty={}, ty0={}, id={:?}, minimum_lifetime={:?})",
1135 hir_id, minimum_lifetime);
1136 self.type_must_outlive(origin, ty, minimum_lifetime);
1139 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1140 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1141 fn link_addr_of(&mut self, expr: &hir::Expr,
1142 mutability: hir::Mutability, base: &hir::Expr) {
1143 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
1145 let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
1147 debug!("link_addr_of: cmt={:?}", cmt);
1149 self.link_region_from_node_type(expr.span, expr.hir_id, mutability, cmt);
1152 /// Computes the guarantors for any ref bindings in a `let` and
1153 /// then ensures that the lifetime of the resulting pointer is
1154 /// linked to the lifetime of the initialization expression.
1155 fn link_local(&self, local: &hir::Local) {
1156 debug!("regionck::for_local()");
1157 let init_expr = match local.init {
1159 Some(ref expr) => &**expr,
1161 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
1162 self.link_pattern(discr_cmt, &local.pat);
1165 /// Computes the guarantors for any ref bindings in a match and
1166 /// then ensures that the lifetime of the resulting pointer is
1167 /// linked to the lifetime of its guarantor (if any).
1168 fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) {
1169 debug!("regionck::for_match()");
1170 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
1171 debug!("discr_cmt={:?}", discr_cmt);
1173 for root_pat in &arm.pats {
1174 self.link_pattern(discr_cmt.clone(), &root_pat);
1179 /// Computes the guarantors for any ref bindings in a match and
1180 /// then ensures that the lifetime of the resulting pointer is
1181 /// linked to the lifetime of its guarantor (if any).
1182 fn link_fn_args(&self, body_scope: region::Scope, args: &[hir::Arg]) {
1183 debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1185 let arg_ty = self.node_ty(arg.hir_id);
1186 let re_scope = self.tcx.mk_region(ty::ReScope(body_scope));
1187 let arg_cmt = self.with_mc(|mc| {
1188 mc.cat_rvalue(arg.id, arg.pat.span, re_scope, arg_ty)
1190 debug!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1194 self.link_pattern(arg_cmt, &arg.pat);
1198 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1199 /// in the discriminant, if needed.
1200 fn link_pattern(&self, discr_cmt: mc::cmt<'tcx>, root_pat: &hir::Pat) {
1201 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1204 let _ = self.with_mc(|mc| {
1205 mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, sub_pat| {
1206 match sub_pat.node {
1208 PatKind::Binding(..) => {
1209 let bm = *mc.tables.pat_binding_modes().get(sub_pat.hir_id)
1210 .expect("missing binding mode");
1211 if let ty::BindByReference(mutbl) = bm {
1212 self.link_region_from_node_type(sub_pat.span, sub_pat.hir_id,
1222 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1224 fn link_autoref(&self,
1226 expr_cmt: mc::cmt<'tcx>,
1227 autoref: &adjustment::AutoBorrow<'tcx>)
1229 debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
1232 adjustment::AutoBorrow::Ref(r, m) => {
1233 self.link_region(expr.span, r,
1234 ty::BorrowKind::from_mutbl(m), expr_cmt);
1237 adjustment::AutoBorrow::RawPtr(m) => {
1238 let r = self.tcx.mk_region(ty::ReScope(region::Scope::Node(expr.hir_id.local_id)));
1239 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1244 /// Like `link_region()`, except that the region is extracted from the type of `id`,
1245 /// which must be some reference (`&T`, `&str`, etc).
1246 fn link_region_from_node_type(&self,
1249 mutbl: hir::Mutability,
1250 cmt_borrowed: mc::cmt<'tcx>) {
1251 debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1252 id, mutbl, cmt_borrowed);
1254 let rptr_ty = self.resolve_node_type(id);
1255 if let ty::TyRef(r, _) = rptr_ty.sty {
1256 debug!("rptr_ty={}", rptr_ty);
1257 self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl),
1262 /// Informs the inference engine that `borrow_cmt` is being borrowed with
1263 /// kind `borrow_kind` and lifetime `borrow_region`.
1264 /// In order to ensure borrowck is satisfied, this may create constraints
1265 /// between regions, as explained in `link_reborrowed_region()`.
1266 fn link_region(&self,
1268 borrow_region: ty::Region<'tcx>,
1269 borrow_kind: ty::BorrowKind,
1270 borrow_cmt: mc::cmt<'tcx>) {
1271 let mut borrow_cmt = borrow_cmt;
1272 let mut borrow_kind = borrow_kind;
1274 let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1275 self.type_must_outlive(origin, borrow_cmt.ty, borrow_region);
1278 debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1282 match borrow_cmt.cat.clone() {
1283 Categorization::Deref(ref_cmt, mc::Implicit(ref_kind, ref_region)) |
1284 Categorization::Deref(ref_cmt, mc::BorrowedPtr(ref_kind, ref_region)) => {
1285 match self.link_reborrowed_region(span,
1286 borrow_region, borrow_kind,
1287 ref_cmt, ref_region, ref_kind,
1299 Categorization::Downcast(cmt_base, _) |
1300 Categorization::Deref(cmt_base, mc::Unique) |
1301 Categorization::Interior(cmt_base, _) => {
1302 // Borrowing interior or owned data requires the base
1303 // to be valid and borrowable in the same fashion.
1304 borrow_cmt = cmt_base;
1305 borrow_kind = borrow_kind;
1308 Categorization::Deref(_, mc::UnsafePtr(..)) |
1309 Categorization::StaticItem |
1310 Categorization::Upvar(..) |
1311 Categorization::Local(..) |
1312 Categorization::Rvalue(..) => {
1313 // These are all "base cases" with independent lifetimes
1314 // that are not subject to inference
1321 /// This is the most complicated case: the path being borrowed is
1322 /// itself the referent of a borrowed pointer. Let me give an
1323 /// example fragment of code to make clear(er) the situation:
1325 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1327 /// &'z *r // the reborrow has lifetime 'z
1329 /// Now, in this case, our primary job is to add the inference
1330 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1331 /// parameters in (roughly) terms of the example:
1333 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1334 /// borrow_region ^~ ref_region ^~
1335 /// borrow_kind ^~ ref_kind ^~
1338 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1340 /// Unfortunately, there are some complications beyond the simple
1341 /// scenario I just painted:
1343 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1344 /// case, we have two jobs. First, we are inferring whether this reference
1345 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1346 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1347 /// then `r` must be an `&mut` reference). Second, whenever we link
1348 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1349 /// case we adjust the cause to indicate that the reference being
1350 /// "reborrowed" is itself an upvar. This provides a nicer error message
1351 /// should something go wrong.
1353 /// 2. There may in fact be more levels of reborrowing. In the
1354 /// example, I said the borrow was like `&'z *r`, but it might
1355 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1356 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1357 /// and `'z <= 'b`. This is explained more below.
1359 /// The return value of this function indicates whether we need to
1360 /// recurse and process `ref_cmt` (see case 2 above).
1361 fn link_reborrowed_region(&self,
1363 borrow_region: ty::Region<'tcx>,
1364 borrow_kind: ty::BorrowKind,
1365 ref_cmt: mc::cmt<'tcx>,
1366 ref_region: ty::Region<'tcx>,
1367 mut ref_kind: ty::BorrowKind,
1369 -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1371 // Possible upvar ID we may need later to create an entry in the
1374 // Detect by-ref upvar `x`:
1375 let cause = match note {
1376 mc::NoteUpvarRef(ref upvar_id) => {
1377 match self.tables.borrow().upvar_capture_map.get(upvar_id) {
1378 Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1379 // The mutability of the upvar may have been modified
1380 // by the above adjustment, so update our local variable.
1381 ref_kind = upvar_borrow.kind;
1383 infer::ReborrowUpvar(span, *upvar_id)
1386 span_bug!( span, "Illegal upvar id: {:?}", upvar_id);
1390 mc::NoteClosureEnv(ref upvar_id) => {
1391 // We don't have any mutability changes to propagate, but
1392 // we do want to note that an upvar reborrow caused this
1394 infer::ReborrowUpvar(span, *upvar_id)
1397 infer::Reborrow(span)
1401 debug!("link_reborrowed_region: {:?} <= {:?}",
1404 self.sub_regions(cause, borrow_region, ref_region);
1406 // If we end up needing to recurse and establish a region link
1407 // with `ref_cmt`, calculate what borrow kind we will end up
1408 // needing. This will be used below.
1410 // One interesting twist is that we can weaken the borrow kind
1411 // when we recurse: to reborrow an `&mut` referent as mutable,
1412 // borrowck requires a unique path to the `&mut` reference but not
1413 // necessarily a *mutable* path.
1414 let new_borrow_kind = match borrow_kind {
1417 ty::MutBorrow | ty::UniqueImmBorrow =>
1421 // Decide whether we need to recurse and link any regions within
1422 // the `ref_cmt`. This is concerned for the case where the value
1423 // being reborrowed is in fact a borrowed pointer found within
1424 // another borrowed pointer. For example:
1426 // let p: &'b &'a mut T = ...;
1430 // What makes this case particularly tricky is that, if the data
1431 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1432 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1433 // (otherwise the user might mutate through the `&mut T` reference
1434 // after `'b` expires and invalidate the borrow we are looking at
1437 // So let's re-examine our parameters in light of this more
1438 // complicated (possible) scenario:
1440 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1441 // borrow_region ^~ ref_region ^~
1442 // borrow_kind ^~ ref_kind ^~
1445 // (Note that since we have not examined `ref_cmt.cat`, we don't
1446 // know whether this scenario has occurred; but I wanted to show
1447 // how all the types get adjusted.)
1450 // The reference being reborrowed is a sharable ref of
1451 // type `&'a T`. In this case, it doesn't matter where we
1452 // *found* the `&T` pointer, the memory it references will
1453 // be valid and immutable for `'a`. So we can stop here.
1455 // (Note that the `borrow_kind` must also be ImmBorrow or
1456 // else the user is borrowed imm memory as mut memory,
1457 // which means they'll get an error downstream in borrowck
1462 ty::MutBorrow | ty::UniqueImmBorrow => {
1463 // The reference being reborrowed is either an `&mut T` or
1464 // `&uniq T`. This is the case where recursion is needed.
1465 return Some((ref_cmt, new_borrow_kind));
1470 /// Checks that the values provided for type/region arguments in a given
1471 /// expression are well-formed and in-scope.
1472 fn substs_wf_in_scope(&mut self,
1473 origin: infer::ParameterOrigin,
1474 substs: &Substs<'tcx>,
1476 expr_region: ty::Region<'tcx>) {
1477 debug!("substs_wf_in_scope(substs={:?}, \
1481 substs, expr_region, origin, expr_span);
1483 let origin = infer::ParameterInScope(origin, expr_span);
1485 for region in substs.regions() {
1486 self.sub_regions(origin.clone(), expr_region, region);
1489 for ty in substs.types() {
1490 let ty = self.resolve_type(ty);
1491 self.type_must_outlive(origin.clone(), ty, expr_region);
1495 /// Ensures that type is well-formed in `region`, which implies (among
1496 /// other things) that all borrowed data reachable via `ty` outlives
1498 pub fn type_must_outlive(&self,
1499 origin: infer::SubregionOrigin<'tcx>,
1501 region: ty::Region<'tcx>)
1503 let ty = self.resolve_type(ty);
1505 debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})",
1510 assert!(!ty.has_escaping_regions());
1512 let components = self.tcx.outlives_components(ty);
1513 self.components_must_outlive(origin, components, region);
1516 fn components_must_outlive(&self,
1517 origin: infer::SubregionOrigin<'tcx>,
1518 components: Vec<Component<'tcx>>,
1519 region: ty::Region<'tcx>)
1521 for component in components {
1522 let origin = origin.clone();
1524 Component::Region(region1) => {
1525 self.sub_regions(origin, region, region1);
1527 Component::Param(param_ty) => {
1528 self.param_ty_must_outlive(origin, region, param_ty);
1530 Component::Projection(projection_ty) => {
1531 self.projection_must_outlive(origin, region, projection_ty);
1533 Component::EscapingProjection(subcomponents) => {
1534 self.components_must_outlive(origin, subcomponents, region);
1536 Component::UnresolvedInferenceVariable(v) => {
1537 // ignore this, we presume it will yield an error
1538 // later, since if a type variable is not resolved by
1539 // this point it never will be
1540 self.tcx.sess.delay_span_bug(
1542 &format!("unresolved inference variable in outlives: {:?}", v));
1548 fn param_ty_must_outlive(&self,
1549 origin: infer::SubregionOrigin<'tcx>,
1550 region: ty::Region<'tcx>,
1551 param_ty: ty::ParamTy) {
1552 debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1553 region, param_ty, origin);
1555 let verify_bound = self.param_bound(param_ty);
1556 let generic = GenericKind::Param(param_ty);
1557 self.verify_generic_bound(origin, generic, region, verify_bound);
1560 fn projection_must_outlive(&self,
1561 origin: infer::SubregionOrigin<'tcx>,
1562 region: ty::Region<'tcx>,
1563 projection_ty: ty::ProjectionTy<'tcx>)
1565 debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1566 region, projection_ty, origin);
1568 // This case is thorny for inference. The fundamental problem is
1569 // that there are many cases where we have choice, and inference
1570 // doesn't like choice (the current region inference in
1571 // particular). :) First off, we have to choose between using the
1572 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1573 // OutlivesProjectionComponent rules, any one of which is
1574 // sufficient. If there are no inference variables involved, it's
1575 // not hard to pick the right rule, but if there are, we're in a
1576 // bit of a catch 22: if we picked which rule we were going to
1577 // use, we could add constraints to the region inference graph
1578 // that make it apply, but if we don't add those constraints, the
1579 // rule might not apply (but another rule might). For now, we err
1580 // on the side of adding too few edges into the graph.
1582 // Compute the bounds we can derive from the environment or trait
1583 // definition. We know that the projection outlives all the
1584 // regions in this list.
1585 let env_bounds = self.projection_declared_bounds(origin.span(), projection_ty);
1587 debug!("projection_must_outlive: env_bounds={:?}",
1590 // If we know that the projection outlives 'static, then we're
1592 if env_bounds.contains(&&ty::ReStatic) {
1593 debug!("projection_must_outlive: 'static as declared bound");
1597 // If declared bounds list is empty, the only applicable rule is
1598 // OutlivesProjectionComponent. If there are inference variables,
1599 // then, we can break down the outlives into more primitive
1600 // components without adding unnecessary edges.
1602 // If there are *no* inference variables, however, we COULD do
1603 // this, but we choose not to, because the error messages are less
1604 // good. For example, a requirement like `T::Item: 'r` would be
1605 // translated to a requirement that `T: 'r`; when this is reported
1606 // to the user, it will thus say "T: 'r must hold so that T::Item:
1607 // 'r holds". But that makes it sound like the only way to fix
1608 // the problem is to add `T: 'r`, which isn't true. So, if there are no
1609 // inference variables, we use a verify constraint instead of adding
1610 // edges, which winds up enforcing the same condition.
1611 let needs_infer = projection_ty.needs_infer();
1612 if env_bounds.is_empty() && needs_infer {
1613 debug!("projection_must_outlive: no declared bounds");
1615 for component_ty in projection_ty.substs.types() {
1616 self.type_must_outlive(origin.clone(), component_ty, region);
1619 for r in projection_ty.substs.regions() {
1620 self.sub_regions(origin.clone(), region, r);
1626 // If we find that there is a unique declared bound `'b`, and this bound
1627 // appears in the trait reference, then the best action is to require that `'b:'r`,
1628 // so do that. This is best no matter what rule we use:
1630 // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1631 // the requirement that `'b:'r`
1632 // - OutlivesProjectionComponent: this would require `'b:'r` in addition to
1634 if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) {
1635 let unique_bound = env_bounds[0];
1636 debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound);
1637 if projection_ty.substs.regions().any(|r| env_bounds.contains(&r)) {
1638 debug!("projection_must_outlive: unique declared bound appears in trait ref");
1639 self.sub_regions(origin.clone(), region, unique_bound);
1644 // Fallback to verifying after the fact that there exists a
1645 // declared bound, or that all the components appearing in the
1646 // projection outlive; in some cases, this may add insufficient
1647 // edges into the inference graph, leading to inference failures
1648 // even though a satisfactory solution exists.
1649 let verify_bound = self.projection_bound(origin.span(), env_bounds, projection_ty);
1650 let generic = GenericKind::Projection(projection_ty);
1651 self.verify_generic_bound(origin, generic.clone(), region, verify_bound);
1654 fn type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1659 ty::TyProjection(data) => {
1660 let declared_bounds = self.projection_declared_bounds(span, data);
1661 self.projection_bound(span, declared_bounds, data)
1664 self.recursive_type_bound(span, ty)
1669 fn param_bound(&self, param_ty: ty::ParamTy) -> VerifyBound<'tcx> {
1670 debug!("param_bound(param_ty={:?})",
1673 let mut param_bounds = self.declared_generic_bounds_from_env(GenericKind::Param(param_ty));
1675 // Add in the default bound of fn body that applies to all in
1676 // scope type parameters:
1677 param_bounds.extend(self.implicit_region_bound);
1679 VerifyBound::AnyRegion(param_bounds)
1682 fn projection_declared_bounds(&self,
1684 projection_ty: ty::ProjectionTy<'tcx>)
1685 -> Vec<ty::Region<'tcx>>
1687 // First assemble bounds from where clauses and traits.
1689 let mut declared_bounds =
1690 self.declared_generic_bounds_from_env(GenericKind::Projection(projection_ty));
1692 declared_bounds.extend_from_slice(
1693 &self.declared_projection_bounds_from_trait(span, projection_ty));
1698 fn projection_bound(&self,
1700 declared_bounds: Vec<ty::Region<'tcx>>,
1701 projection_ty: ty::ProjectionTy<'tcx>)
1702 -> VerifyBound<'tcx> {
1703 debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1704 declared_bounds, projection_ty);
1706 // see the extensive comment in projection_must_outlive
1707 let ty = self.tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs);
1708 let recursive_bound = self.recursive_type_bound(span, ty);
1710 VerifyBound::AnyRegion(declared_bounds).or(recursive_bound)
1713 fn recursive_type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1714 let mut bounds = vec![];
1716 for subty in ty.walk_shallow() {
1717 bounds.push(self.type_bound(span, subty));
1720 let mut regions = ty.regions();
1721 regions.retain(|r| !r.is_late_bound()); // ignore late-bound regions
1722 bounds.push(VerifyBound::AllRegions(regions));
1724 // remove bounds that must hold, since they are not interesting
1725 bounds.retain(|b| !b.must_hold());
1727 if bounds.len() == 1 {
1728 bounds.pop().unwrap()
1730 VerifyBound::AllBounds(bounds)
1734 fn declared_generic_bounds_from_env(&self, generic: GenericKind<'tcx>)
1735 -> Vec<ty::Region<'tcx>>
1737 let param_env = &self.param_env;
1739 // To start, collect bounds from user:
1740 let mut param_bounds = self.tcx.required_region_bounds(generic.to_ty(self.tcx),
1741 param_env.caller_bounds.to_vec());
1743 // Next, collect regions we scraped from the well-formedness
1744 // constraints in the fn signature. To do that, we walk the list
1745 // of known relations from the fn ctxt.
1747 // This is crucial because otherwise code like this fails:
1749 // fn foo<'a, A>(x: &'a A) { x.bar() }
1751 // The problem is that the type of `x` is `&'a A`. To be
1752 // well-formed, then, A must be lower-generic by `'a`, but we
1753 // don't know that this holds from first principles.
1754 for &(r, p) in &self.region_bound_pairs {
1755 debug!("generic={:?} p={:?}",
1759 param_bounds.push(r);
1766 fn declared_projection_bounds_from_trait(&self,
1768 projection_ty: ty::ProjectionTy<'tcx>)
1769 -> Vec<ty::Region<'tcx>>
1771 debug!("projection_bounds(projection_ty={:?})",
1773 let ty = self.tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs);
1775 // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1776 // in looking for a trait definition like:
1779 // trait SomeTrait<'a> {
1780 // type SomeType : 'a;
1784 // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1785 let trait_predicates = self.tcx.predicates_of(projection_ty.trait_ref(self.tcx).def_id);
1786 assert_eq!(trait_predicates.parent, None);
1787 let predicates = trait_predicates.predicates.as_slice().to_vec();
1788 traits::elaborate_predicates(self.tcx, predicates)
1789 .filter_map(|predicate| {
1790 // we're only interesting in `T : 'a` style predicates:
1791 let outlives = match predicate {
1792 ty::Predicate::TypeOutlives(data) => data,
1793 _ => { return None; }
1796 debug!("projection_bounds: outlives={:?} (1)",
1799 // apply the substitutions (and normalize any projected types)
1800 let outlives = self.instantiate_type_scheme(span,
1801 projection_ty.substs,
1804 debug!("projection_bounds: outlives={:?} (2)",
1807 let region_result = self.commit_if_ok(|_| {
1809 self.replace_late_bound_regions_with_fresh_var(
1811 infer::AssocTypeProjection(projection_ty.item_def_id),
1814 debug!("projection_bounds: outlives={:?} (3)",
1817 // check whether this predicate applies to our current projection
1818 let cause = self.fcx.misc(span);
1819 match self.at(&cause, self.fcx.param_env).eq(outlives.0, ty) {
1820 Ok(ok) => Ok((ok, outlives.1)),
1823 }).map(|(ok, result)| {
1824 self.register_infer_ok_obligations(ok);
1828 debug!("projection_bounds: region_result={:?}",