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: int }
63 //! struct Bar { foo: Foo }
64 //! fn get_i(x: &'a Bar) -> &'a int {
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 owned pointers. We say that the guarantor
80 //! of such data it 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
88 use middle
::free_region
::FreeRegionMap
;
89 use middle
::implicator
;
90 use middle
::mem_categorization
as mc
;
91 use middle
::region
::CodeExtent
;
92 use middle
::subst
::Substs
;
94 use middle
::ty
::{self, ClosureTyper, ReScope, Ty, MethodCall}
;
95 use middle
::infer
::{self, GenericKind}
;
97 use util
::ppaux
::{ty_to_string, Repr}
;
100 use syntax
::{ast, ast_util}
;
101 use syntax
::codemap
::Span
;
103 use syntax
::visit
::Visitor
;
105 use self::SubjectNode
::Subject
;
107 // a variation on try that just returns unit
108 macro_rules
! ignore_err
{
109 ($e
:expr
) => (match $e { Ok(e) => e, Err(_) => return () }
)
112 ///////////////////////////////////////////////////////////////////////////
113 // PUBLIC ENTRY POINTS
115 pub fn regionck_expr(fcx
: &FnCtxt
, e
: &ast
::Expr
) {
116 let mut rcx
= Rcx
::new(fcx
, RepeatingScope(e
.id
), e
.id
, Subject(e
.id
));
117 if fcx
.err_count_since_creation() == 0 {
118 // regionck assumes typeck succeeded
120 rcx
.visit_region_obligations(e
.id
);
122 rcx
.resolve_regions_and_report_errors();
125 pub fn regionck_item(fcx
: &FnCtxt
, item
: &ast
::Item
) {
126 let mut rcx
= Rcx
::new(fcx
, RepeatingScope(item
.id
), item
.id
, Subject(item
.id
));
128 rcx
.free_region_map
.relate_free_regions_from_predicates(tcx
, &fcx
.inh
.param_env
.caller_bounds
);
129 rcx
.visit_region_obligations(item
.id
);
130 rcx
.resolve_regions_and_report_errors();
133 pub fn regionck_fn(fcx
: &FnCtxt
,
138 debug
!("regionck_fn(id={})", fn_id
);
139 let mut rcx
= Rcx
::new(fcx
, RepeatingScope(blk
.id
), blk
.id
, Subject(fn_id
));
141 if fcx
.err_count_since_creation() == 0 {
142 // regionck assumes typeck succeeded
143 rcx
.visit_fn_body(fn_id
, decl
, blk
, fn_span
);
147 rcx
.free_region_map
.relate_free_regions_from_predicates(tcx
, &fcx
.inh
.param_env
.caller_bounds
);
149 rcx
.resolve_regions_and_report_errors();
151 // For the top-level fn, store the free-region-map. We don't store
152 // any map for closures; they just share the same map as the
153 // function that created them.
154 fcx
.tcx().store_free_region_map(fn_id
, rcx
.free_region_map
);
157 /// Checks that the types in `component_tys` are well-formed. This will add constraints into the
158 /// region graph. Does *not* run `resolve_regions_and_report_errors` and so forth.
159 pub fn regionck_ensure_component_tys_wf
<'a
, 'tcx
>(fcx
: &FnCtxt
<'a
, 'tcx
>,
161 component_tys
: &[Ty
<'tcx
>]) {
162 let mut rcx
= Rcx
::new(fcx
, RepeatingScope(0), 0, SubjectNode
::None
);
163 for &component_ty
in component_tys
{
164 // Check that each type outlives the empty region. Since the
165 // empty region is a subregion of all others, this can't fail
166 // unless the type does not meet the well-formedness
168 type_must_outlive(&mut rcx
, infer
::RelateParamBound(span
, component_ty
),
169 component_ty
, ty
::ReEmpty
);
173 ///////////////////////////////////////////////////////////////////////////
176 pub struct Rcx
<'a
, 'tcx
: 'a
> {
177 fcx
: &'a FnCtxt
<'a
, 'tcx
>,
179 region_bound_pairs
: Vec
<(ty
::Region
, GenericKind
<'tcx
>)>,
181 free_region_map
: FreeRegionMap
,
183 // id of innermost fn body id
184 body_id
: ast
::NodeId
,
186 // id of innermost fn or loop
187 repeating_scope
: ast
::NodeId
,
189 // id of AST node being analyzed (the subject of the analysis).
190 subject
: SubjectNode
,
194 pub struct RepeatingScope(ast
::NodeId
);
195 pub enum SubjectNode { Subject(ast::NodeId), None }
197 impl<'a
, 'tcx
> Rcx
<'a
, 'tcx
> {
198 pub fn new(fcx
: &'a FnCtxt
<'a
, 'tcx
>,
199 initial_repeating_scope
: RepeatingScope
,
200 initial_body_id
: ast
::NodeId
,
201 subject
: SubjectNode
) -> Rcx
<'a
, 'tcx
> {
202 let RepeatingScope(initial_repeating_scope
) = initial_repeating_scope
;
204 repeating_scope
: initial_repeating_scope
,
205 body_id
: initial_body_id
,
207 region_bound_pairs
: Vec
::new(),
208 free_region_map
: FreeRegionMap
::new(),
212 pub fn tcx(&self) -> &'a ty
::ctxt
<'tcx
> {
216 fn set_body_id(&mut self, body_id
: ast
::NodeId
) -> ast
::NodeId
{
217 mem
::replace(&mut self.body_id
, body_id
)
220 fn set_repeating_scope(&mut self, scope
: ast
::NodeId
) -> ast
::NodeId
{
221 mem
::replace(&mut self.repeating_scope
, scope
)
224 /// Try to resolve the type for the given node, returning t_err if an error results. Note that
225 /// we never care about the details of the error, the same error will be detected and reported
226 /// in the writeback phase.
228 /// Note one important point: we do not attempt to resolve *region variables* here. This is
229 /// because regionck is essentially adding constraints to those region variables and so may yet
230 /// influence how they are resolved.
232 /// Consider this silly example:
235 /// fn borrow(x: &int) -> &int {x}
236 /// fn foo(x: @int) -> int { // block: B
237 /// let b = borrow(x); // region: <R0>
242 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
243 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
244 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
245 /// of b will be `&<R0>.int` and then `*b` will require that `<R0>` be bigger than the let and
246 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
247 pub fn resolve_type(&self, unresolved_ty
: Ty
<'tcx
>) -> Ty
<'tcx
> {
248 self.fcx
.infcx().resolve_type_vars_if_possible(&unresolved_ty
)
251 /// Try to resolve the type for the given node.
252 fn resolve_node_type(&self, id
: ast
::NodeId
) -> Ty
<'tcx
> {
253 let t
= self.fcx
.node_ty(id
);
257 fn resolve_method_type(&self, method_call
: MethodCall
) -> Option
<Ty
<'tcx
>> {
258 let method_ty
= self.fcx
.inh
.method_map
.borrow()
259 .get(&method_call
).map(|method
| method
.ty
);
260 method_ty
.map(|method_ty
| self.resolve_type(method_ty
))
263 /// Try to resolve the type for the given node.
264 pub fn resolve_expr_type_adjusted(&mut self, expr
: &ast
::Expr
) -> Ty
<'tcx
> {
265 let ty_unadjusted
= self.resolve_node_type(expr
.id
);
266 if ty
::type_is_error(ty_unadjusted
) {
269 let tcx
= self.fcx
.tcx();
270 ty
::adjust_ty(tcx
, expr
.span
, expr
.id
, ty_unadjusted
,
271 self.fcx
.inh
.adjustments
.borrow().get(&expr
.id
),
272 |method_call
| self.resolve_method_type(method_call
))
276 fn visit_fn_body(&mut self,
278 fn_decl
: &ast
::FnDecl
,
282 // When we enter a function, we can derive
283 debug
!("visit_fn_body(id={})", id
);
285 let fn_sig_map
= self.fcx
.inh
.fn_sig_map
.borrow();
286 let fn_sig
= match fn_sig_map
.get(&id
) {
290 &format
!("No fn-sig entry for id={}", id
));
294 let old_region_bounds_pairs_len
= self.region_bound_pairs
.len();
296 let old_body_id
= self.set_body_id(body
.id
);
297 self.relate_free_regions(&fn_sig
[..], body
.id
, span
);
298 link_fn_args(self, CodeExtent
::from_node_id(body
.id
), &fn_decl
.inputs
[..]);
299 self.visit_block(body
);
300 self.visit_region_obligations(body
.id
);
302 self.region_bound_pairs
.truncate(old_region_bounds_pairs_len
);
304 self.set_body_id(old_body_id
);
307 fn visit_region_obligations(&mut self, node_id
: ast
::NodeId
)
309 debug
!("visit_region_obligations: node_id={}", node_id
);
311 // region checking can introduce new pending obligations
312 // which, when processed, might generate new region
313 // obligations. So make sure we process those.
314 self.fcx
.select_all_obligations_or_error();
316 // Make a copy of the region obligations vec because we'll need
317 // to be able to borrow the fulfillment-cx below when projecting.
318 let region_obligations
=
319 self.fcx
.inh
.fulfillment_cx
.borrow()
320 .region_obligations(node_id
)
323 for r_o
in ®ion_obligations
{
324 debug
!("visit_region_obligations: r_o={}",
325 r_o
.repr(self.tcx()));
326 let sup_type
= self.resolve_type(r_o
.sup_type
);
327 let origin
= infer
::RelateParamBound(r_o
.cause
.span
, sup_type
);
328 type_must_outlive(self, origin
, sup_type
, r_o
.sub_region
);
331 // Processing the region obligations should not cause the list to grow further:
332 assert_eq
!(region_obligations
.len(),
333 self.fcx
.inh
.fulfillment_cx
.borrow().region_obligations(node_id
).len());
336 /// This method populates the region map's `free_region_map`. It walks over the transformed
337 /// argument and return types for each function just before we check the body of that function,
338 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
339 /// [usize]`. We do not allow references to outlive the things they point at, so we can assume
340 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
341 /// the caller side, the caller is responsible for checking that the type of every expression
342 /// (including the actual values for the arguments, as well as the return type of the fn call)
345 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
346 fn relate_free_regions(&mut self,
347 fn_sig_tys
: &[Ty
<'tcx
>],
348 body_id
: ast
::NodeId
,
350 debug
!("relate_free_regions >>");
351 let tcx
= self.tcx();
353 for &ty
in fn_sig_tys
{
354 let ty
= self.resolve_type(ty
);
355 debug
!("relate_free_regions(t={})", ty
.repr(tcx
));
356 let body_scope
= CodeExtent
::from_node_id(body_id
);
357 let body_scope
= ty
::ReScope(body_scope
);
358 let implications
= implicator
::implications(self.fcx
.infcx(), self.fcx
, body_id
,
359 ty
, body_scope
, span
);
361 // Record any relations between free regions that we observe into the free-region-map.
362 self.free_region_map
.relate_free_regions_from_implications(tcx
, &implications
);
364 // But also record other relationships, such as `T:'x`,
365 // that don't go into the free-region-map but which we use
367 for implication
in implications
{
368 debug
!("implication: {}", implication
.repr(tcx
));
370 implicator
::Implication
::RegionSubRegion(_
,
372 ty
::ReInfer(ty
::ReVar(vid_b
))) => {
373 self.fcx
.inh
.infcx
.add_given(free_a
, vid_b
);
375 implicator
::Implication
::RegionSubGeneric(_
, r_a
, ref generic_b
) => {
376 debug
!("RegionSubGeneric: {} <= {}",
377 r_a
.repr(tcx
), generic_b
.repr(tcx
));
379 self.region_bound_pairs
.push((r_a
, generic_b
.clone()));
381 implicator
::Implication
::RegionSubRegion(..) |
382 implicator
::Implication
::RegionSubClosure(..) |
383 implicator
::Implication
::Predicate(..) => {
384 // In principle, we could record (and take
385 // advantage of) every relationship here, but
386 // we are also free not to -- it simply means
387 // strictly less that we can successfully type
388 // check. (It may also be that we should
389 // revise our inference system to be more
390 // general and to make use of *every*
391 // relationship that arises here, but
392 // presently we do not.)
398 debug
!("<< relate_free_regions");
401 fn resolve_regions_and_report_errors(&self) {
402 let subject_node_id
= match self.subject
{
404 SubjectNode
::None
=> {
405 self.tcx().sess
.bug("cannot resolve_regions_and_report_errors \
406 without subject node");
410 self.fcx
.infcx().resolve_regions_and_report_errors(&self.free_region_map
,
415 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for Rcx
<'a
, 'tcx
> {
416 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
417 // However, right now we run into an issue whereby some free
418 // regions are not properly related if they appear within the
419 // types of arguments that must be inferred. This could be
420 // addressed by deferring the construction of the region
421 // hierarchy, and in particular the relationships between free
422 // regions, until regionck, as described in #3238.
424 fn visit_fn(&mut self, _fk
: visit
::FnKind
<'v
>, fd
: &'v ast
::FnDecl
,
425 b
: &'v ast
::Block
, span
: Span
, id
: ast
::NodeId
) {
426 self.visit_fn_body(id
, fd
, b
, span
)
429 fn visit_item(&mut self, i
: &ast
::Item
) { visit_item(self, i); }
431 fn visit_expr(&mut self, ex
: &ast
::Expr
) { visit_expr(self, ex); }
433 //visit_pat: visit_pat, // (..) see above
435 fn visit_arm(&mut self, a
: &ast
::Arm
) { visit_arm(self, a); }
437 fn visit_local(&mut self, l
: &ast
::Local
) { visit_local(self, l); }
439 fn visit_block(&mut self, b
: &ast
::Block
) { visit_block(self, b); }
442 fn visit_item(_rcx
: &mut Rcx
, _item
: &ast
::Item
) {
446 fn visit_block(rcx
: &mut Rcx
, b
: &ast
::Block
) {
447 visit
::walk_block(rcx
, b
);
450 fn visit_arm(rcx
: &mut Rcx
, arm
: &ast
::Arm
) {
453 constrain_bindings_in_pat(&**p
, rcx
);
456 visit
::walk_arm(rcx
, arm
);
459 fn visit_local(rcx
: &mut Rcx
, l
: &ast
::Local
) {
461 constrain_bindings_in_pat(&*l
.pat
, rcx
);
463 visit
::walk_local(rcx
, l
);
466 fn constrain_bindings_in_pat(pat
: &ast
::Pat
, rcx
: &mut Rcx
) {
467 let tcx
= rcx
.fcx
.tcx();
468 debug
!("regionck::visit_pat(pat={})", pat
.repr(tcx
));
469 pat_util
::pat_bindings(&tcx
.def_map
, pat
, |_
, id
, span
, _
| {
470 // If we have a variable that contains region'd data, that
471 // data will be accessible from anywhere that the variable is
472 // accessed. We must be wary of loops like this:
474 // // from src/test/compile-fail/borrowck-lend-flow.rs
475 // let mut v = box 3, w = box 4;
476 // let mut x = &mut w;
479 // borrow(v); //~ ERROR cannot borrow
480 // x = &mut v; // (1)
483 // Typically, we try to determine the region of a borrow from
484 // those points where it is dereferenced. In this case, one
485 // might imagine that the lifetime of `x` need only be the
486 // body of the loop. But of course this is incorrect because
487 // the pointer that is created at point (1) is consumed at
488 // point (2), meaning that it must be live across the loop
489 // iteration. The easiest way to guarantee this is to require
490 // that the lifetime of any regions that appear in a
491 // variable's type enclose at least the variable's scope.
493 let var_region
= tcx
.region_maps
.var_region(id
);
494 type_of_node_must_outlive(
495 rcx
, infer
::BindingTypeIsNotValidAtDecl(span
),
498 let var_scope
= tcx
.region_maps
.var_scope(id
);
499 let typ
= rcx
.resolve_node_type(id
);
500 dropck
::check_safety_of_destructor_if_necessary(rcx
, typ
, span
, var_scope
);
504 fn visit_expr(rcx
: &mut Rcx
, expr
: &ast
::Expr
) {
505 debug
!("regionck::visit_expr(e={}, repeating_scope={})",
506 expr
.repr(rcx
.fcx
.tcx()), rcx
.repeating_scope
);
508 // No matter what, the type of each expression must outlive the
509 // scope of that expression. This also guarantees basic WF.
510 let expr_ty
= rcx
.resolve_node_type(expr
.id
);
512 type_must_outlive(rcx
, infer
::ExprTypeIsNotInScope(expr_ty
, expr
.span
),
513 expr_ty
, ty
::ReScope(CodeExtent
::from_node_id(expr
.id
)));
515 let method_call
= MethodCall
::expr(expr
.id
);
516 let has_method_map
= rcx
.fcx
.inh
.method_map
.borrow().contains_key(&method_call
);
518 // Check any autoderefs or autorefs that appear.
519 if let Some(adjustment
) = rcx
.fcx
.inh
.adjustments
.borrow().get(&expr
.id
) {
520 debug
!("adjustment={:?}", adjustment
);
522 ty
::AdjustDerefRef(ty
::AutoDerefRef {autoderefs, ref autoref, ..}
) => {
523 let expr_ty
= rcx
.resolve_node_type(expr
.id
);
524 constrain_autoderefs(rcx
, expr
, autoderefs
, expr_ty
);
525 if let Some(ref autoref
) = *autoref
{
526 link_autoref(rcx
, expr
, autoderefs
, autoref
);
528 // Require that the resulting region encompasses
531 // FIXME(#6268) remove to support nested method calls
532 type_of_node_must_outlive(
533 rcx
, infer
::AutoBorrow(expr
.span
),
534 expr
.id
, ty
::ReScope(CodeExtent
::from_node_id(expr
.id
)));
538 ty::AutoObject(_, ref bounds, _, _) => {
539 // Determine if we are casting `expr` to a trait
540 // instance. If so, we have to be sure that the type
541 // of the source obeys the new region bound.
542 let source_ty = rcx.resolve_node_type(expr.id);
543 type_must_outlive(rcx, infer::RelateObjectBound(expr.span),
544 source_ty, bounds.region_bound);
550 // If necessary, constrain destructors in the unadjusted form of this
553 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
);
554 mc
.cat_expr_unadjusted(expr
)
558 check_safety_of_rvalue_destructor_if_necessary(rcx
,
563 let tcx
= rcx
.fcx
.tcx();
564 tcx
.sess
.delay_span_bug(expr
.span
, "cat_expr_unadjusted Errd");
569 // If necessary, constrain destructors in this expression. This will be
570 // the adjusted form if there is an adjustment.
572 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
);
577 check_safety_of_rvalue_destructor_if_necessary(rcx
, head_cmt
, expr
.span
);
580 let tcx
= rcx
.fcx
.tcx();
581 tcx
.sess
.delay_span_bug(expr
.span
, "cat_expr Errd");
586 ast
::ExprCall(ref callee
, ref args
) => {
588 constrain_call(rcx
, expr
, Some(&**callee
),
589 args
.iter().map(|e
| &**e
), false);
591 constrain_callee(rcx
, callee
.id
, expr
, &**callee
);
592 constrain_call(rcx
, expr
, None
,
593 args
.iter().map(|e
| &**e
), false);
596 visit
::walk_expr(rcx
, expr
);
599 ast
::ExprMethodCall(_
, _
, ref args
) => {
600 constrain_call(rcx
, expr
, Some(&*args
[0]),
601 args
[1..].iter().map(|e
| &**e
), false);
603 visit
::walk_expr(rcx
, expr
);
606 ast
::ExprAssignOp(_
, ref lhs
, ref rhs
) => {
608 constrain_call(rcx
, expr
, Some(&**lhs
),
609 Some(&**rhs
).into_iter(), true);
612 visit
::walk_expr(rcx
, expr
);
615 ast
::ExprIndex(ref lhs
, ref rhs
) if has_method_map
=> {
616 constrain_call(rcx
, expr
, Some(&**lhs
),
617 Some(&**rhs
).into_iter(), true);
619 visit
::walk_expr(rcx
, expr
);
622 ast
::ExprBinary(op
, ref lhs
, ref rhs
) if has_method_map
=> {
623 let implicitly_ref_args
= !ast_util
::is_by_value_binop(op
.node
);
625 // As `expr_method_call`, but the call is via an
626 // overloaded op. Note that we (sadly) currently use an
627 // implicit "by ref" sort of passing style here. This
628 // should be converted to an adjustment!
629 constrain_call(rcx
, expr
, Some(&**lhs
),
630 Some(&**rhs
).into_iter(), implicitly_ref_args
);
632 visit
::walk_expr(rcx
, expr
);
635 ast
::ExprBinary(_
, ref lhs
, ref rhs
) => {
636 // If you do `x OP y`, then the types of `x` and `y` must
637 // outlive the operation you are performing.
638 let lhs_ty
= rcx
.resolve_expr_type_adjusted(&**lhs
);
639 let rhs_ty
= rcx
.resolve_expr_type_adjusted(&**rhs
);
640 for &ty
in [lhs_ty
, rhs_ty
].iter() {
641 type_must_outlive(rcx
,
642 infer
::Operand(expr
.span
),
644 ty
::ReScope(CodeExtent
::from_node_id(expr
.id
)));
646 visit
::walk_expr(rcx
, expr
);
649 ast
::ExprUnary(op
, ref lhs
) if has_method_map
=> {
650 let implicitly_ref_args
= !ast_util
::is_by_value_unop(op
);
653 constrain_call(rcx
, expr
, Some(&**lhs
),
654 None
::<ast
::Expr
>.iter(), implicitly_ref_args
);
656 visit
::walk_expr(rcx
, expr
);
659 ast
::ExprUnary(ast
::UnDeref
, ref base
) => {
660 // For *a, the lifetime of a must enclose the deref
661 let method_call
= MethodCall
::expr(expr
.id
);
662 let base_ty
= match rcx
.fcx
.inh
.method_map
.borrow().get(&method_call
) {
664 constrain_call(rcx
, expr
, Some(&**base
),
665 None
::<ast
::Expr
>.iter(), true);
666 let fn_ret
= // late-bound regions in overloaded method calls are instantiated
667 ty
::no_late_bound_regions(rcx
.tcx(), &ty
::ty_fn_ret(method
.ty
)).unwrap();
670 None
=> rcx
.resolve_node_type(base
.id
)
672 if let ty
::ty_rptr(r_ptr
, _
) = base_ty
.sty
{
673 mk_subregion_due_to_dereference(
674 rcx
, expr
.span
, ty
::ReScope(CodeExtent
::from_node_id(expr
.id
)), *r_ptr
);
677 visit
::walk_expr(rcx
, expr
);
680 ast
::ExprIndex(ref vec_expr
, _
) => {
681 // For a[b], the lifetime of a must enclose the deref
682 let vec_type
= rcx
.resolve_expr_type_adjusted(&**vec_expr
);
683 constrain_index(rcx
, expr
, vec_type
);
685 visit
::walk_expr(rcx
, expr
);
688 ast
::ExprCast(ref source
, _
) => {
689 // Determine if we are casting `source` to a trait
690 // instance. If so, we have to be sure that the type of
691 // the source obeys the trait's region bound.
692 constrain_cast(rcx
, expr
, &**source
);
693 visit
::walk_expr(rcx
, expr
);
696 ast
::ExprAddrOf(m
, ref base
) => {
697 link_addr_of(rcx
, expr
, m
, &**base
);
699 // Require that when you write a `&expr` expression, the
700 // resulting pointer has a lifetime that encompasses the
701 // `&expr` expression itself. Note that we constraining
702 // the type of the node expr.id here *before applying
705 // FIXME(#6268) nested method calls requires that this rule change
706 let ty0
= rcx
.resolve_node_type(expr
.id
);
707 type_must_outlive(rcx
, infer
::AddrOf(expr
.span
),
708 ty0
, ty
::ReScope(CodeExtent
::from_node_id(expr
.id
)));
709 visit
::walk_expr(rcx
, expr
);
712 ast
::ExprMatch(ref discr
, ref arms
, _
) => {
713 link_match(rcx
, &**discr
, &arms
[..]);
715 visit
::walk_expr(rcx
, expr
);
718 ast
::ExprClosure(_
, _
, ref body
) => {
719 check_expr_fn_block(rcx
, expr
, &**body
);
722 ast
::ExprLoop(ref body
, _
) => {
723 let repeating_scope
= rcx
.set_repeating_scope(body
.id
);
724 visit
::walk_expr(rcx
, expr
);
725 rcx
.set_repeating_scope(repeating_scope
);
728 ast
::ExprWhile(ref cond
, ref body
, _
) => {
729 let repeating_scope
= rcx
.set_repeating_scope(cond
.id
);
730 rcx
.visit_expr(&**cond
);
732 rcx
.set_repeating_scope(body
.id
);
733 rcx
.visit_block(&**body
);
735 rcx
.set_repeating_scope(repeating_scope
);
739 visit
::walk_expr(rcx
, expr
);
744 fn constrain_cast(rcx
: &mut Rcx
,
745 cast_expr
: &ast
::Expr
,
746 source_expr
: &ast
::Expr
)
748 debug
!("constrain_cast(cast_expr={}, source_expr={})",
749 cast_expr
.repr(rcx
.tcx()),
750 source_expr
.repr(rcx
.tcx()));
752 let source_ty
= rcx
.resolve_node_type(source_expr
.id
);
753 let target_ty
= rcx
.resolve_node_type(cast_expr
.id
);
755 walk_cast(rcx
, cast_expr
, source_ty
, target_ty
);
757 fn walk_cast
<'a
, 'tcx
>(rcx
: &mut Rcx
<'a
, 'tcx
>,
758 cast_expr
: &ast
::Expr
,
761 debug
!("walk_cast(from_ty={}, to_ty={})",
762 from_ty
.repr(rcx
.tcx()),
763 to_ty
.repr(rcx
.tcx()));
764 match (&from_ty
.sty
, &to_ty
.sty
) {
765 /*From:*/ (&ty
::ty_rptr(from_r
, ref from_mt
),
766 /*To: */ &ty
::ty_rptr(to_r
, ref to_mt
)) => {
767 // Target cannot outlive source, naturally.
768 rcx
.fcx
.mk_subr(infer
::Reborrow(cast_expr
.span
), *to_r
, *from_r
);
769 walk_cast(rcx
, cast_expr
, from_mt
.ty
, to_mt
.ty
);
773 /*To: */ &ty
::ty_trait(box ty
::TyTrait { ref bounds, .. }
)) => {
774 // When T is existentially quantified as a trait
775 // `Foo+'to`, it must outlive the region bound `'to`.
776 type_must_outlive(rcx
, infer
::RelateObjectBound(cast_expr
.span
),
777 from_ty
, bounds
.region_bound
);
780 /*From:*/ (&ty
::ty_uniq(from_referent_ty
),
781 /*To: */ &ty
::ty_uniq(to_referent_ty
)) => {
782 walk_cast(rcx
, cast_expr
, from_referent_ty
, to_referent_ty
);
790 fn check_expr_fn_block(rcx
: &mut Rcx
,
793 let repeating_scope
= rcx
.set_repeating_scope(body
.id
);
794 visit
::walk_expr(rcx
, expr
);
795 rcx
.set_repeating_scope(repeating_scope
);
798 fn constrain_callee(rcx
: &mut Rcx
,
799 callee_id
: ast
::NodeId
,
800 _call_expr
: &ast
::Expr
,
801 _callee_expr
: &ast
::Expr
) {
802 let callee_ty
= rcx
.resolve_node_type(callee_id
);
803 match callee_ty
.sty
{
804 ty
::ty_bare_fn(..) => { }
806 // this should not happen, but it does if the program is
809 // tcx.sess.span_bug(
811 // format!("Calling non-function: {}", callee_ty.repr(tcx)));
816 fn constrain_call
<'a
, I
: Iterator
<Item
=&'a ast
::Expr
>>(rcx
: &mut Rcx
,
817 call_expr
: &ast
::Expr
,
818 receiver
: Option
<&ast
::Expr
>,
820 implicitly_ref_args
: bool
) {
821 //! Invoked on every call site (i.e., normal calls, method calls,
822 //! and overloaded operators). Constrains the regions which appear
823 //! in the type of the function. Also constrains the regions that
824 //! appear in the arguments appropriately.
826 let tcx
= rcx
.fcx
.tcx();
827 debug
!("constrain_call(call_expr={}, \
829 implicitly_ref_args={})",
832 implicitly_ref_args
);
834 // `callee_region` is the scope representing the time in which the
837 // FIXME(#6268) to support nested method calls, should be callee_id
838 let callee_scope
= CodeExtent
::from_node_id(call_expr
.id
);
839 let callee_region
= ty
::ReScope(callee_scope
);
841 debug
!("callee_region={}", callee_region
.repr(tcx
));
843 for arg_expr
in arg_exprs
{
844 debug
!("Argument: {}", arg_expr
.repr(tcx
));
846 // ensure that any regions appearing in the argument type are
847 // valid for at least the lifetime of the function:
848 type_of_node_must_outlive(
849 rcx
, infer
::CallArg(arg_expr
.span
),
850 arg_expr
.id
, callee_region
);
852 // unfortunately, there are two means of taking implicit
853 // references, and we need to propagate constraints as a
854 // result. modes are going away and the "DerefArgs" code
855 // should be ported to use adjustments
856 if implicitly_ref_args
{
857 link_by_ref(rcx
, arg_expr
, callee_scope
);
861 // as loop above, but for receiver
862 if let Some(r
) = receiver
{
863 debug
!("receiver: {}", r
.repr(tcx
));
864 type_of_node_must_outlive(
865 rcx
, infer
::CallRcvr(r
.span
),
866 r
.id
, callee_region
);
867 if implicitly_ref_args
{
868 link_by_ref(rcx
, &*r
, callee_scope
);
873 /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being
874 /// dereferenced, the lifetime of the pointer includes the deref expr.
875 fn constrain_autoderefs
<'a
, 'tcx
>(rcx
: &mut Rcx
<'a
, 'tcx
>,
876 deref_expr
: &ast
::Expr
,
878 mut derefd_ty
: Ty
<'tcx
>)
880 debug
!("constrain_autoderefs(deref_expr={}, derefs={}, derefd_ty={})",
881 deref_expr
.repr(rcx
.tcx()),
883 derefd_ty
.repr(rcx
.tcx()));
885 let r_deref_expr
= ty
::ReScope(CodeExtent
::from_node_id(deref_expr
.id
));
887 let method_call
= MethodCall
::autoderef(deref_expr
.id
, i
as u32);
888 debug
!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call
, derefs
);
890 derefd_ty
= match rcx
.fcx
.inh
.method_map
.borrow().get(&method_call
) {
892 debug
!("constrain_autoderefs: #{} is overloaded, method={}",
893 i
, method
.repr(rcx
.tcx()));
895 // Treat overloaded autoderefs as if an AutoRef adjustment
896 // was applied on the base type, as that is always the case.
897 let fn_sig
= ty
::ty_fn_sig(method
.ty
);
898 let fn_sig
= // late-bound regions should have been instantiated
899 ty
::no_late_bound_regions(rcx
.tcx(), fn_sig
).unwrap();
900 let self_ty
= fn_sig
.inputs
[0];
901 let (m
, r
) = match self_ty
.sty
{
902 ty
::ty_rptr(r
, ref m
) => (m
.mutbl
, r
),
904 rcx
.tcx().sess
.span_bug(
906 &format
!("bad overloaded deref type {}",
907 method
.ty
.repr(rcx
.tcx())))
911 debug
!("constrain_autoderefs: receiver r={:?} m={:?}",
912 r
.repr(rcx
.tcx()), m
);
915 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
);
916 let self_cmt
= ignore_err
!(mc
.cat_expr_autoderefd(deref_expr
, i
));
917 debug
!("constrain_autoderefs: self_cmt={:?}",
918 self_cmt
.repr(rcx
.tcx()));
919 link_region(rcx
, deref_expr
.span
, r
,
920 ty
::BorrowKind
::from_mutbl(m
), self_cmt
);
923 // Specialized version of constrain_call.
924 type_must_outlive(rcx
, infer
::CallRcvr(deref_expr
.span
),
925 self_ty
, r_deref_expr
);
926 match fn_sig
.output
{
927 ty
::FnConverging(return_type
) => {
928 type_must_outlive(rcx
, infer
::CallReturn(deref_expr
.span
),
929 return_type
, r_deref_expr
);
932 ty
::FnDiverging
=> unreachable
!()
938 if let ty
::ty_rptr(r_ptr
, _
) = derefd_ty
.sty
{
939 mk_subregion_due_to_dereference(rcx
, deref_expr
.span
,
940 r_deref_expr
, *r_ptr
);
943 match ty
::deref(derefd_ty
, true) {
944 Some(mt
) => derefd_ty
= mt
.ty
,
945 /* if this type can't be dereferenced, then there's already an error
946 in the session saying so. Just bail out for now */
952 pub fn mk_subregion_due_to_dereference(rcx
: &mut Rcx
,
954 minimum_lifetime
: ty
::Region
,
955 maximum_lifetime
: ty
::Region
) {
956 rcx
.fcx
.mk_subr(infer
::DerefPointer(deref_span
),
957 minimum_lifetime
, maximum_lifetime
)
960 fn check_safety_of_rvalue_destructor_if_necessary
<'a
, 'tcx
>(rcx
: &mut Rcx
<'a
, 'tcx
>,
964 mc
::cat_rvalue(region
) => {
966 ty
::ReScope(rvalue_scope
) => {
967 let typ
= rcx
.resolve_type(cmt
.ty
);
968 dropck
::check_safety_of_destructor_if_necessary(rcx
,
978 &format
!("unexpected rvalue region in rvalue \
979 destructor safety checking: `{}`",
980 region
.repr(rcx
.tcx())));
988 /// Invoked on any index expression that occurs. Checks that if this is a slice being indexed, the
989 /// lifetime of the pointer includes the deref expr.
990 fn constrain_index
<'a
, 'tcx
>(rcx
: &mut Rcx
<'a
, 'tcx
>,
991 index_expr
: &ast
::Expr
,
992 indexed_ty
: Ty
<'tcx
>)
994 debug
!("constrain_index(index_expr=?, indexed_ty={}",
995 rcx
.fcx
.infcx().ty_to_string(indexed_ty
));
997 let r_index_expr
= ty
::ReScope(CodeExtent
::from_node_id(index_expr
.id
));
998 if let ty
::ty_rptr(r_ptr
, mt
) = indexed_ty
.sty
{
1000 ty
::ty_vec(_
, None
) | ty
::ty_str
=> {
1001 rcx
.fcx
.mk_subr(infer
::IndexSlice(index_expr
.span
),
1002 r_index_expr
, *r_ptr
);
1009 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1010 /// adjustments) are valid for at least `minimum_lifetime`
1011 fn type_of_node_must_outlive
<'a
, 'tcx
>(
1012 rcx
: &mut Rcx
<'a
, 'tcx
>,
1013 origin
: infer
::SubregionOrigin
<'tcx
>,
1015 minimum_lifetime
: ty
::Region
)
1017 let tcx
= rcx
.fcx
.tcx();
1019 // Try to resolve the type. If we encounter an error, then typeck
1020 // is going to fail anyway, so just stop here and let typeck
1021 // report errors later on in the writeback phase.
1022 let ty0
= rcx
.resolve_node_type(id
);
1023 let ty
= ty
::adjust_ty(tcx
, origin
.span(), id
, ty0
,
1024 rcx
.fcx
.inh
.adjustments
.borrow().get(&id
),
1025 |method_call
| rcx
.resolve_method_type(method_call
));
1026 debug
!("constrain_regions_in_type_of_node(\
1027 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
1028 ty_to_string(tcx
, ty
), ty_to_string(tcx
, ty0
),
1029 id
, minimum_lifetime
);
1030 type_must_outlive(rcx
, origin
, ty
, minimum_lifetime
);
1033 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1034 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1035 fn link_addr_of(rcx
: &mut Rcx
, expr
: &ast
::Expr
,
1036 mutability
: ast
::Mutability
, base
: &ast
::Expr
) {
1037 debug
!("link_addr_of(expr={}, base={})", expr
.repr(rcx
.tcx()), base
.repr(rcx
.tcx()));
1040 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
);
1041 ignore_err
!(mc
.cat_expr(base
))
1044 debug
!("link_addr_of: cmt={}", cmt
.repr(rcx
.tcx()));
1046 link_region_from_node_type(rcx
, expr
.span
, expr
.id
, mutability
, cmt
);
1049 /// Computes the guarantors for any ref bindings in a `let` and
1050 /// then ensures that the lifetime of the resulting pointer is
1051 /// linked to the lifetime of the initialization expression.
1052 fn link_local(rcx
: &Rcx
, local
: &ast
::Local
) {
1053 debug
!("regionck::for_local()");
1054 let init_expr
= match local
.init
{
1056 Some(ref expr
) => &**expr
,
1058 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
);
1059 let discr_cmt
= ignore_err
!(mc
.cat_expr(init_expr
));
1060 link_pattern(rcx
, mc
, discr_cmt
, &*local
.pat
);
1063 /// Computes the guarantors for any ref bindings in a match and
1064 /// then ensures that the lifetime of the resulting pointer is
1065 /// linked to the lifetime of its guarantor (if any).
1066 fn link_match(rcx
: &Rcx
, discr
: &ast
::Expr
, arms
: &[ast
::Arm
]) {
1067 debug
!("regionck::for_match()");
1068 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
);
1069 let discr_cmt
= ignore_err
!(mc
.cat_expr(discr
));
1070 debug
!("discr_cmt={}", discr_cmt
.repr(rcx
.tcx()));
1072 for root_pat
in &arm
.pats
{
1073 link_pattern(rcx
, mc
, discr_cmt
.clone(), &**root_pat
);
1078 /// Computes the guarantors for any ref bindings in a match and
1079 /// then ensures that the lifetime of the resulting pointer is
1080 /// linked to the lifetime of its guarantor (if any).
1081 fn link_fn_args(rcx
: &Rcx
, body_scope
: CodeExtent
, args
: &[ast
::Arg
]) {
1082 debug
!("regionck::link_fn_args(body_scope={:?})", body_scope
);
1083 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
);
1085 let arg_ty
= rcx
.fcx
.node_ty(arg
.id
);
1086 let re_scope
= ty
::ReScope(body_scope
);
1087 let arg_cmt
= mc
.cat_rvalue(arg
.id
, arg
.ty
.span
, re_scope
, arg_ty
);
1088 debug
!("arg_ty={} arg_cmt={}",
1089 arg_ty
.repr(rcx
.tcx()),
1090 arg_cmt
.repr(rcx
.tcx()));
1091 link_pattern(rcx
, mc
, arg_cmt
, &*arg
.pat
);
1095 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found in the discriminant, if
1097 fn link_pattern
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1098 mc
: mc
::MemCategorizationContext
<FnCtxt
<'a
, 'tcx
>>,
1099 discr_cmt
: mc
::cmt
<'tcx
>,
1100 root_pat
: &ast
::Pat
) {
1101 debug
!("link_pattern(discr_cmt={}, root_pat={})",
1102 discr_cmt
.repr(rcx
.tcx()),
1103 root_pat
.repr(rcx
.tcx()));
1104 let _
= mc
.cat_pattern(discr_cmt
, root_pat
, |mc
, sub_cmt
, sub_pat
| {
1105 match sub_pat
.node
{
1107 ast
::PatIdent(ast
::BindByRef(mutbl
), _
, _
) => {
1108 link_region_from_node_type(
1109 rcx
, sub_pat
.span
, sub_pat
.id
,
1113 // `[_, ..slice, _]` pattern
1114 ast
::PatVec(_
, Some(ref slice_pat
), _
) => {
1115 match mc
.cat_slice_pattern(sub_cmt
, &**slice_pat
) {
1116 Ok((slice_cmt
, slice_mutbl
, slice_r
)) => {
1117 link_region(rcx
, sub_pat
.span
, &slice_r
,
1118 ty
::BorrowKind
::from_mutbl(slice_mutbl
),
1129 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1131 fn link_autoref(rcx
: &Rcx
,
1134 autoref
: &ty
::AutoRef
)
1136 debug
!("link_autoref(autoref={:?})", autoref
);
1137 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
);
1138 let expr_cmt
= ignore_err
!(mc
.cat_expr_autoderefd(expr
, autoderefs
));
1139 debug
!("expr_cmt={}", expr_cmt
.repr(rcx
.tcx()));
1142 ty
::AutoPtr(r
, m
) => {
1143 link_region(rcx
, expr
.span
, r
,
1144 ty
::BorrowKind
::from_mutbl(m
), expr_cmt
);
1147 ty
::AutoUnsafe(m
) => {
1148 let r
= ty
::ReScope(CodeExtent
::from_node_id(expr
.id
));
1149 link_region(rcx
, expr
.span
, &r
, ty
::BorrowKind
::from_mutbl(m
), expr_cmt
);
1154 /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and
1155 /// must outlive `callee_scope`.
1156 fn link_by_ref(rcx
: &Rcx
,
1158 callee_scope
: CodeExtent
) {
1159 let tcx
= rcx
.tcx();
1160 debug
!("link_by_ref(expr={}, callee_scope={:?})",
1161 expr
.repr(tcx
), callee_scope
);
1162 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
);
1163 let expr_cmt
= ignore_err
!(mc
.cat_expr(expr
));
1164 let borrow_region
= ty
::ReScope(callee_scope
);
1165 link_region(rcx
, expr
.span
, &borrow_region
, ty
::ImmBorrow
, expr_cmt
);
1168 /// Like `link_region()`, except that the region is extracted from the type of `id`, which must be
1169 /// some reference (`&T`, `&str`, etc).
1170 fn link_region_from_node_type
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1173 mutbl
: ast
::Mutability
,
1174 cmt_borrowed
: mc
::cmt
<'tcx
>) {
1175 debug
!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={})",
1176 id
, mutbl
, cmt_borrowed
.repr(rcx
.tcx()));
1178 let rptr_ty
= rcx
.resolve_node_type(id
);
1179 if !ty
::type_is_error(rptr_ty
) {
1180 let tcx
= rcx
.fcx
.ccx
.tcx
;
1181 debug
!("rptr_ty={}", ty_to_string(tcx
, rptr_ty
));
1182 let r
= ty
::ty_region(tcx
, span
, rptr_ty
);
1183 link_region(rcx
, span
, &r
, ty
::BorrowKind
::from_mutbl(mutbl
),
1188 /// Informs the inference engine that `borrow_cmt` is being borrowed with kind `borrow_kind` and
1189 /// lifetime `borrow_region`. In order to ensure borrowck is satisfied, this may create constraints
1190 /// between regions, as explained in `link_reborrowed_region()`.
1191 fn link_region
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1193 borrow_region
: &ty
::Region
,
1194 borrow_kind
: ty
::BorrowKind
,
1195 borrow_cmt
: mc
::cmt
<'tcx
>) {
1196 let mut borrow_cmt
= borrow_cmt
;
1197 let mut borrow_kind
= borrow_kind
;
1200 debug
!("link_region(borrow_region={}, borrow_kind={}, borrow_cmt={})",
1201 borrow_region
.repr(rcx
.tcx()),
1202 borrow_kind
.repr(rcx
.tcx()),
1203 borrow_cmt
.repr(rcx
.tcx()));
1204 match borrow_cmt
.cat
.clone() {
1205 mc
::cat_deref(ref_cmt
, _
,
1206 mc
::Implicit(ref_kind
, ref_region
)) |
1207 mc
::cat_deref(ref_cmt
, _
,
1208 mc
::BorrowedPtr(ref_kind
, ref_region
)) => {
1209 match link_reborrowed_region(rcx
, span
,
1210 borrow_region
, borrow_kind
,
1211 ref_cmt
, ref_region
, ref_kind
,
1223 mc
::cat_downcast(cmt_base
, _
) |
1224 mc
::cat_deref(cmt_base
, _
, mc
::Unique
) |
1225 mc
::cat_interior(cmt_base
, _
) => {
1226 // Borrowing interior or owned data requires the base
1227 // to be valid and borrowable in the same fashion.
1228 borrow_cmt
= cmt_base
;
1229 borrow_kind
= borrow_kind
;
1232 mc
::cat_deref(_
, _
, mc
::UnsafePtr(..)) |
1233 mc
::cat_static_item
|
1236 mc
::cat_rvalue(..) => {
1237 // These are all "base cases" with independent lifetimes
1238 // that are not subject to inference
1245 /// This is the most complicated case: the path being borrowed is
1246 /// itself the referent of a borrowed pointer. Let me give an
1247 /// example fragment of code to make clear(er) the situation:
1249 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1251 /// &'z *r // the reborrow has lifetime 'z
1253 /// Now, in this case, our primary job is to add the inference
1254 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1255 /// parameters in (roughly) terms of the example:
1257 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1258 /// borrow_region ^~ ref_region ^~
1259 /// borrow_kind ^~ ref_kind ^~
1262 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1264 /// Unfortunately, there are some complications beyond the simple
1265 /// scenario I just painted:
1267 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1268 /// case, we have two jobs. First, we are inferring whether this reference
1269 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1270 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1271 /// then `r` must be an `&mut` reference). Second, whenever we link
1272 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1273 /// case we adjust the cause to indicate that the reference being
1274 /// "reborrowed" is itself an upvar. This provides a nicer error message
1275 /// should something go wrong.
1277 /// 2. There may in fact be more levels of reborrowing. In the
1278 /// example, I said the borrow was like `&'z *r`, but it might
1279 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1280 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1281 /// and `'z <= 'b`. This is explained more below.
1283 /// The return value of this function indicates whether we need to
1284 /// recurse and process `ref_cmt` (see case 2 above).
1285 fn link_reborrowed_region
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1287 borrow_region
: &ty
::Region
,
1288 borrow_kind
: ty
::BorrowKind
,
1289 ref_cmt
: mc
::cmt
<'tcx
>,
1290 ref_region
: ty
::Region
,
1291 mut ref_kind
: ty
::BorrowKind
,
1293 -> Option
<(mc
::cmt
<'tcx
>, ty
::BorrowKind
)>
1295 // Possible upvar ID we may need later to create an entry in the
1298 // Detect by-ref upvar `x`:
1299 let cause
= match note
{
1300 mc
::NoteUpvarRef(ref upvar_id
) => {
1301 let upvar_capture_map
= rcx
.fcx
.inh
.upvar_capture_map
.borrow_mut();
1302 match upvar_capture_map
.get(upvar_id
) {
1303 Some(&ty
::UpvarCapture
::ByRef(ref upvar_borrow
)) => {
1304 // The mutability of the upvar may have been modified
1305 // by the above adjustment, so update our local variable.
1306 ref_kind
= upvar_borrow
.kind
;
1308 infer
::ReborrowUpvar(span
, *upvar_id
)
1311 rcx
.tcx().sess
.span_bug(
1313 &format
!("Illegal upvar id: {}",
1314 upvar_id
.repr(rcx
.tcx())));
1318 mc
::NoteClosureEnv(ref upvar_id
) => {
1319 // We don't have any mutability changes to propagate, but
1320 // we do want to note that an upvar reborrow caused this
1322 infer
::ReborrowUpvar(span
, *upvar_id
)
1325 infer
::Reborrow(span
)
1329 debug
!("link_reborrowed_region: {} <= {}",
1330 borrow_region
.repr(rcx
.tcx()),
1331 ref_region
.repr(rcx
.tcx()));
1332 rcx
.fcx
.mk_subr(cause
, *borrow_region
, ref_region
);
1334 // If we end up needing to recurse and establish a region link
1335 // with `ref_cmt`, calculate what borrow kind we will end up
1336 // needing. This will be used below.
1338 // One interesting twist is that we can weaken the borrow kind
1339 // when we recurse: to reborrow an `&mut` referent as mutable,
1340 // borrowck requires a unique path to the `&mut` reference but not
1341 // necessarily a *mutable* path.
1342 let new_borrow_kind
= match borrow_kind
{
1345 ty
::MutBorrow
| ty
::UniqueImmBorrow
=>
1349 // Decide whether we need to recurse and link any regions within
1350 // the `ref_cmt`. This is concerned for the case where the value
1351 // being reborrowed is in fact a borrowed pointer found within
1352 // another borrowed pointer. For example:
1354 // let p: &'b &'a mut T = ...;
1358 // What makes this case particularly tricky is that, if the data
1359 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1360 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1361 // (otherwise the user might mutate through the `&mut T` reference
1362 // after `'b` expires and invalidate the borrow we are looking at
1365 // So let's re-examine our parameters in light of this more
1366 // complicated (possible) scenario:
1368 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1369 // borrow_region ^~ ref_region ^~
1370 // borrow_kind ^~ ref_kind ^~
1373 // (Note that since we have not examined `ref_cmt.cat`, we don't
1374 // know whether this scenario has occurred; but I wanted to show
1375 // how all the types get adjusted.)
1378 // The reference being reborrowed is a sharable ref of
1379 // type `&'a T`. In this case, it doesn't matter where we
1380 // *found* the `&T` pointer, the memory it references will
1381 // be valid and immutable for `'a`. So we can stop here.
1383 // (Note that the `borrow_kind` must also be ImmBorrow or
1384 // else the user is borrowed imm memory as mut memory,
1385 // which means they'll get an error downstream in borrowck
1390 ty
::MutBorrow
| ty
::UniqueImmBorrow
=> {
1391 // The reference being reborrowed is either an `&mut T` or
1392 // `&uniq T`. This is the case where recursion is needed.
1393 return Some((ref_cmt
, new_borrow_kind
));
1398 /// Ensures that all borrowed data reachable via `ty` outlives `region`.
1399 pub fn type_must_outlive
<'a
, 'tcx
>(rcx
: &mut Rcx
<'a
, 'tcx
>,
1400 origin
: infer
::SubregionOrigin
<'tcx
>,
1404 debug
!("type_must_outlive(ty={}, region={})",
1406 region
.repr(rcx
.tcx()));
1408 let implications
= implicator
::implications(rcx
.fcx
.infcx(), rcx
.fcx
, rcx
.body_id
,
1409 ty
, region
, origin
.span());
1410 for implication
in implications
{
1411 debug
!("implication: {}", implication
.repr(rcx
.tcx()));
1413 implicator
::Implication
::RegionSubRegion(None
, r_a
, r_b
) => {
1414 rcx
.fcx
.mk_subr(origin
.clone(), r_a
, r_b
);
1416 implicator
::Implication
::RegionSubRegion(Some(ty
), r_a
, r_b
) => {
1417 let o1
= infer
::ReferenceOutlivesReferent(ty
, origin
.span());
1418 rcx
.fcx
.mk_subr(o1
, r_a
, r_b
);
1420 implicator
::Implication
::RegionSubGeneric(None
, r_a
, ref generic_b
) => {
1421 generic_must_outlive(rcx
, origin
.clone(), r_a
, generic_b
);
1423 implicator
::Implication
::RegionSubGeneric(Some(ty
), r_a
, ref generic_b
) => {
1424 let o1
= infer
::ReferenceOutlivesReferent(ty
, origin
.span());
1425 generic_must_outlive(rcx
, o1
, r_a
, generic_b
);
1427 implicator
::Implication
::RegionSubClosure(_
, r_a
, def_id
, substs
) => {
1428 closure_must_outlive(rcx
, origin
.clone(), r_a
, def_id
, substs
);
1430 implicator
::Implication
::Predicate(def_id
, predicate
) => {
1431 let cause
= traits
::ObligationCause
::new(origin
.span(),
1433 traits
::ItemObligation(def_id
));
1434 let obligation
= traits
::Obligation
::new(cause
, predicate
);
1435 rcx
.fcx
.register_predicate(obligation
);
1441 fn closure_must_outlive
<'a
, 'tcx
>(rcx
: &mut Rcx
<'a
, 'tcx
>,
1442 origin
: infer
::SubregionOrigin
<'tcx
>,
1445 substs
: &'tcx Substs
<'tcx
>) {
1446 debug
!("closure_must_outlive(region={}, def_id={}, substs={})",
1447 region
.repr(rcx
.tcx()), def_id
.repr(rcx
.tcx()), substs
.repr(rcx
.tcx()));
1449 let upvars
= rcx
.fcx
.closure_upvars(def_id
, substs
).unwrap();
1450 for upvar
in upvars
{
1451 let var_id
= upvar
.def
.def_id().local_id();
1453 rcx
, infer
::FreeVariable(origin
.span(), var_id
),
1458 fn generic_must_outlive
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1459 origin
: infer
::SubregionOrigin
<'tcx
>,
1461 generic
: &GenericKind
<'tcx
>) {
1462 let param_env
= &rcx
.fcx
.inh
.param_env
;
1464 debug
!("param_must_outlive(region={}, generic={})",
1465 region
.repr(rcx
.tcx()),
1466 generic
.repr(rcx
.tcx()));
1468 // To start, collect bounds from user:
1469 let mut param_bounds
=
1470 ty
::required_region_bounds(rcx
.tcx(),
1471 generic
.to_ty(rcx
.tcx()),
1472 param_env
.caller_bounds
.clone());
1474 // In the case of a projection T::Foo, we may be able to extract bounds from the trait def:
1476 GenericKind
::Param(..) => { }
1477 GenericKind
::Projection(ref projection_ty
) => {
1478 param_bounds
.push_all(
1479 &projection_bounds(rcx
, origin
.span(), projection_ty
));
1483 // Add in the default bound of fn body that applies to all in
1484 // scope type parameters:
1485 param_bounds
.push(param_env
.implicit_region_bound
);
1487 // Finally, collect regions we scraped from the well-formedness
1488 // constraints in the fn signature. To do that, we walk the list
1489 // of known relations from the fn ctxt.
1491 // This is crucial because otherwise code like this fails:
1493 // fn foo<'a, A>(x: &'a A) { x.bar() }
1495 // The problem is that the type of `x` is `&'a A`. To be
1496 // well-formed, then, A must be lower-generic by `'a`, but we
1497 // don't know that this holds from first principles.
1498 for &(ref r
, ref p
) in &rcx
.region_bound_pairs
{
1499 debug
!("generic={} p={}",
1500 generic
.repr(rcx
.tcx()),
1503 param_bounds
.push(*r
);
1507 // Inform region inference that this generic must be properly
1509 rcx
.fcx
.infcx().verify_generic_bound(origin
,
1515 fn projection_bounds
<'a
,'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1517 projection_ty
: &ty
::ProjectionTy
<'tcx
>)
1521 let tcx
= fcx
.tcx();
1522 let infcx
= fcx
.infcx();
1524 debug
!("projection_bounds(projection_ty={})",
1525 projection_ty
.repr(tcx
));
1527 let ty
= ty
::mk_projection(tcx
, projection_ty
.trait_ref
.clone(), projection_ty
.item_name
);
1529 // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1530 // in looking for a trait definition like:
1533 // trait SomeTrait<'a> {
1534 // type SomeType : 'a;
1538 // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1539 let trait_predicates
= ty
::lookup_predicates(tcx
, projection_ty
.trait_ref
.def_id
);
1540 let predicates
= trait_predicates
.predicates
.as_slice().to_vec();
1541 traits
::elaborate_predicates(tcx
, predicates
)
1542 .filter_map(|predicate
| {
1543 // we're only interesting in `T : 'a` style predicates:
1544 let outlives
= match predicate
{
1545 ty
::Predicate
::TypeOutlives(data
) => data
,
1546 _
=> { return None; }
1549 debug
!("projection_bounds: outlives={} (1)",
1550 outlives
.repr(tcx
));
1552 // apply the substitutions (and normalize any projected types)
1553 let outlives
= fcx
.instantiate_type_scheme(span
,
1554 projection_ty
.trait_ref
.substs
,
1557 debug
!("projection_bounds: outlives={} (2)",
1558 outlives
.repr(tcx
));
1560 let region_result
= infcx
.commit_if_ok(|_
| {
1562 infcx
.replace_late_bound_regions_with_fresh_var(
1564 infer
::AssocTypeProjection(projection_ty
.item_name
),
1567 debug
!("projection_bounds: outlives={} (3)",
1568 outlives
.repr(tcx
));
1570 // check whether this predicate applies to our current projection
1571 match infer
::mk_eqty(infcx
, false, infer
::Misc(span
), ty
, outlives
.0) {
1572 Ok(()) => { Ok(outlives.1) }
1573 Err(_
) => { Err(()) }
1577 debug
!("projection_bounds: region_result={}",
1578 region_result
.repr(tcx
));