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
88 use middle
::free_region
::FreeRegionMap
;
89 use middle
::mem_categorization
as mc
;
90 use middle
::mem_categorization
::Categorization
;
91 use middle
::region
::{self, CodeExtent}
;
92 use middle
::subst
::Substs
;
94 use middle
::ty
::{self, Ty, MethodCall, TypeFoldable}
;
95 use middle
::infer
::{self, GenericKind, InferCtxt, SubregionOrigin, TypeOrigin, VerifyBound}
;
97 use middle
::ty
::adjustment
;
98 use middle
::ty
::wf
::ImpliedBound
;
102 use syntax
::codemap
::Span
;
103 use rustc_front
::intravisit
::{self, Visitor}
;
104 use rustc_front
::hir
::{self, PatKind}
;
105 use rustc_front
::util
as hir_util
;
107 use self::SubjectNode
::Subject
;
109 // a variation on try that just returns unit
110 macro_rules
! ignore_err
{
111 ($e
:expr
) => (match $e { Ok(e) => e, Err(_) => return () }
)
114 ///////////////////////////////////////////////////////////////////////////
115 // PUBLIC ENTRY POINTS
117 pub fn regionck_expr(fcx
: &FnCtxt
, e
: &hir
::Expr
) {
118 let mut rcx
= Rcx
::new(fcx
, RepeatingScope(e
.id
), e
.id
, Subject(e
.id
));
119 if fcx
.err_count_since_creation() == 0 {
120 // regionck assumes typeck succeeded
122 rcx
.visit_region_obligations(e
.id
);
124 rcx
.resolve_regions_and_report_errors();
127 /// Region checking during the WF phase for items. `wf_tys` are the
128 /// types from which we should derive implied bounds, if any.
129 pub fn regionck_item
<'a
,'tcx
>(fcx
: &FnCtxt
<'a
,'tcx
>,
130 item_id
: ast
::NodeId
,
132 wf_tys
: &[Ty
<'tcx
>]) {
133 debug
!("regionck_item(item.id={:?}, wf_tys={:?}", item_id
, wf_tys
);
134 let mut rcx
= Rcx
::new(fcx
, RepeatingScope(item_id
), item_id
, Subject(item_id
));
137 .relate_free_regions_from_predicates(tcx
, &fcx
.infcx().parameter_environment
.caller_bounds
);
138 rcx
.relate_free_regions(wf_tys
, item_id
, span
);
139 rcx
.visit_region_obligations(item_id
);
140 rcx
.resolve_regions_and_report_errors();
143 pub fn regionck_fn(fcx
: &FnCtxt
,
148 debug
!("regionck_fn(id={})", fn_id
);
149 let mut rcx
= Rcx
::new(fcx
, RepeatingScope(blk
.id
), blk
.id
, Subject(fn_id
));
151 if fcx
.err_count_since_creation() == 0 {
152 // regionck assumes typeck succeeded
153 rcx
.visit_fn_body(fn_id
, decl
, blk
, fn_span
);
158 .relate_free_regions_from_predicates(tcx
, &fcx
.infcx().parameter_environment
.caller_bounds
);
160 rcx
.resolve_regions_and_report_errors();
162 // For the top-level fn, store the free-region-map. We don't store
163 // any map for closures; they just share the same map as the
164 // function that created them.
165 fcx
.tcx().store_free_region_map(fn_id
, rcx
.free_region_map
);
168 ///////////////////////////////////////////////////////////////////////////
171 pub struct Rcx
<'a
, 'tcx
: 'a
> {
172 pub fcx
: &'a FnCtxt
<'a
, 'tcx
>,
174 region_bound_pairs
: Vec
<(ty
::Region
, GenericKind
<'tcx
>)>,
176 free_region_map
: FreeRegionMap
,
178 // id of innermost fn body id
179 body_id
: ast
::NodeId
,
181 // call_site scope of innermost fn
182 call_site_scope
: Option
<CodeExtent
>,
184 // id of innermost fn or loop
185 repeating_scope
: ast
::NodeId
,
187 // id of AST node being analyzed (the subject of the analysis).
188 subject
: SubjectNode
,
192 pub struct RepeatingScope(ast
::NodeId
);
193 pub enum SubjectNode { Subject(ast::NodeId), None }
195 impl<'a
, 'tcx
> Rcx
<'a
, 'tcx
> {
196 pub fn new(fcx
: &'a FnCtxt
<'a
, 'tcx
>,
197 initial_repeating_scope
: RepeatingScope
,
198 initial_body_id
: ast
::NodeId
,
199 subject
: SubjectNode
) -> Rcx
<'a
, 'tcx
> {
200 let RepeatingScope(initial_repeating_scope
) = initial_repeating_scope
;
202 repeating_scope
: initial_repeating_scope
,
203 body_id
: initial_body_id
,
204 call_site_scope
: None
,
206 region_bound_pairs
: Vec
::new(),
207 free_region_map
: FreeRegionMap
::new(),
211 pub fn tcx(&self) -> &'a ty
::ctxt
<'tcx
> {
215 pub fn infcx(&self) -> &InferCtxt
<'a
,'tcx
> {
219 fn set_call_site_scope(&mut self, call_site_scope
: Option
<CodeExtent
>) -> Option
<CodeExtent
> {
220 mem
::replace(&mut self.call_site_scope
, call_site_scope
)
223 fn set_body_id(&mut self, body_id
: ast
::NodeId
) -> ast
::NodeId
{
224 mem
::replace(&mut self.body_id
, body_id
)
227 fn set_repeating_scope(&mut self, scope
: ast
::NodeId
) -> ast
::NodeId
{
228 mem
::replace(&mut self.repeating_scope
, scope
)
231 /// Try to resolve the type for the given node, returning t_err if an error results. Note that
232 /// we never care about the details of the error, the same error will be detected and reported
233 /// in the writeback phase.
235 /// Note one important point: we do not attempt to resolve *region variables* here. This is
236 /// because regionck is essentially adding constraints to those region variables and so may yet
237 /// influence how they are resolved.
239 /// Consider this silly example:
242 /// fn borrow(x: &i32) -> &i32 {x}
243 /// fn foo(x: @i32) -> i32 { // block: B
244 /// let b = borrow(x); // region: <R0>
249 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
250 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
251 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
252 /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
253 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
254 pub fn resolve_type(&self, unresolved_ty
: Ty
<'tcx
>) -> Ty
<'tcx
> {
255 self.fcx
.infcx().resolve_type_vars_if_possible(&unresolved_ty
)
258 /// Try to resolve the type for the given node.
259 fn resolve_node_type(&self, id
: ast
::NodeId
) -> Ty
<'tcx
> {
260 let t
= self.fcx
.node_ty(id
);
264 fn resolve_method_type(&self, method_call
: MethodCall
) -> Option
<Ty
<'tcx
>> {
265 let method_ty
= self.fcx
.inh
.tables
.borrow().method_map
266 .get(&method_call
).map(|method
| method
.ty
);
267 method_ty
.map(|method_ty
| self.resolve_type(method_ty
))
270 /// Try to resolve the type for the given node.
271 pub fn resolve_expr_type_adjusted(&mut self, expr
: &hir
::Expr
) -> Ty
<'tcx
> {
272 let ty_unadjusted
= self.resolve_node_type(expr
.id
);
273 if ty_unadjusted
.references_error() {
276 ty_unadjusted
.adjust(
277 self.fcx
.tcx(), expr
.span
, expr
.id
,
278 self.fcx
.inh
.tables
.borrow().adjustments
.get(&expr
.id
),
279 |method_call
| self.resolve_method_type(method_call
))
283 fn visit_fn_body(&mut self,
284 id
: ast
::NodeId
, // the id of the fn itself
285 fn_decl
: &hir
::FnDecl
,
289 // When we enter a function, we can derive
290 debug
!("visit_fn_body(id={})", id
);
292 let call_site
= self.fcx
.tcx().region_maps
.lookup_code_extent(
293 region
::CodeExtentData
::CallSiteScope { fn_id: id, body_id: body.id }
);
294 let old_call_site_scope
= self.set_call_site_scope(Some(call_site
));
297 let fn_sig_map
= &self.infcx().tables
.borrow().liberated_fn_sigs
;
298 match fn_sig_map
.get(&id
) {
299 Some(f
) => f
.clone(),
302 &format
!("No fn-sig entry for id={}", id
));
307 let old_region_bounds_pairs_len
= self.region_bound_pairs
.len();
309 // Collect the types from which we create inferred bounds.
310 // For the return type, if diverging, substitute `bool` just
311 // because it will have no effect.
313 // FIXME(#27579) return types should not be implied bounds
314 let fn_sig_tys
: Vec
<_
> =
317 .chain(Some(fn_sig
.output
.unwrap_or(self.tcx().types
.bool
)))
320 let old_body_id
= self.set_body_id(body
.id
);
321 self.relate_free_regions(&fn_sig_tys
[..], body
.id
, span
);
323 self.tcx().region_maps
.node_extent(body
.id
),
324 &fn_decl
.inputs
[..]);
325 self.visit_block(body
);
326 self.visit_region_obligations(body
.id
);
328 let call_site_scope
= self.call_site_scope
.unwrap();
329 debug
!("visit_fn_body body.id {} call_site_scope: {:?}",
330 body
.id
, call_site_scope
);
331 type_of_node_must_outlive(self,
332 infer
::CallReturn(span
),
334 ty
::ReScope(call_site_scope
));
336 self.region_bound_pairs
.truncate(old_region_bounds_pairs_len
);
338 self.set_body_id(old_body_id
);
339 self.set_call_site_scope(old_call_site_scope
);
342 fn visit_region_obligations(&mut self, node_id
: ast
::NodeId
)
344 debug
!("visit_region_obligations: node_id={}", node_id
);
346 // region checking can introduce new pending obligations
347 // which, when processed, might generate new region
348 // obligations. So make sure we process those.
349 self.fcx
.select_all_obligations_or_error();
351 // Make a copy of the region obligations vec because we'll need
352 // to be able to borrow the fulfillment-cx below when projecting.
353 let region_obligations
=
358 .region_obligations(node_id
)
361 for r_o
in ®ion_obligations
{
362 debug
!("visit_region_obligations: r_o={:?} cause={:?}",
364 let sup_type
= self.resolve_type(r_o
.sup_type
);
365 let origin
= self.code_to_origin(r_o
.cause
.span
, sup_type
, &r_o
.cause
.code
);
366 type_must_outlive(self, origin
, sup_type
, r_o
.sub_region
);
369 // Processing the region obligations should not cause the list to grow further:
370 assert_eq
!(region_obligations
.len(),
371 self.fcx
.inh
.fulfillment_cx
.borrow().region_obligations(node_id
).len());
374 fn code_to_origin(&self,
377 code
: &traits
::ObligationCauseCode
<'tcx
>)
378 -> SubregionOrigin
<'tcx
> {
380 traits
::ObligationCauseCode
::ReferenceOutlivesReferent(ref_type
) =>
381 infer
::ReferenceOutlivesReferent(ref_type
, span
),
383 infer
::RelateParamBound(span
, sup_type
),
387 /// This method populates the region map's `free_region_map`. It walks over the transformed
388 /// argument and return types for each function just before we check the body of that function,
389 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
390 /// [usize]`. We do not allow references to outlive the things they point at, so we can assume
391 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
392 /// the caller side, the caller is responsible for checking that the type of every expression
393 /// (including the actual values for the arguments, as well as the return type of the fn call)
396 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
397 fn relate_free_regions(&mut self,
398 fn_sig_tys
: &[Ty
<'tcx
>],
399 body_id
: ast
::NodeId
,
401 debug
!("relate_free_regions >>");
403 for &ty
in fn_sig_tys
{
404 let ty
= self.resolve_type(ty
);
405 debug
!("relate_free_regions(t={:?})", ty
);
406 let implied_bounds
= ty
::wf
::implied_bounds(self.fcx
.infcx(), body_id
, ty
, span
);
408 // Record any relations between free regions that we observe into the free-region-map.
409 self.free_region_map
.relate_free_regions_from_implied_bounds(&implied_bounds
);
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(ty
::ReFree(free_a
),
418 ty
::ReVar(vid_b
)) => {
419 self.fcx
.inh
.infcx
.add_given(free_a
, vid_b
);
421 ImpliedBound
::RegionSubParam(r_a
, param_b
) => {
422 self.region_bound_pairs
.push((r_a
, GenericKind
::Param(param_b
)));
424 ImpliedBound
::RegionSubProjection(r_a
, projection_b
) => {
425 self.region_bound_pairs
.push((r_a
, GenericKind
::Projection(projection_b
)));
427 ImpliedBound
::RegionSubRegion(..) => {
428 // In principle, we could record (and take
429 // advantage of) every relationship here, but
430 // we are also free not to -- it simply means
431 // strictly less that we can successfully type
432 // check. (It may also be that we should
433 // revise our inference system to be more
434 // general and to make use of *every*
435 // relationship that arises here, but
436 // presently we do not.)
442 debug
!("<< relate_free_regions");
445 fn resolve_regions_and_report_errors(&self) {
446 let subject_node_id
= match self.subject
{
448 SubjectNode
::None
=> {
449 self.tcx().sess
.bug("cannot resolve_regions_and_report_errors \
450 without subject node");
454 self.fcx
.infcx().resolve_regions_and_report_errors(&self.free_region_map
,
459 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for Rcx
<'a
, 'tcx
> {
460 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
461 // However, right now we run into an issue whereby some free
462 // regions are not properly related if they appear within the
463 // types of arguments that must be inferred. This could be
464 // addressed by deferring the construction of the region
465 // hierarchy, and in particular the relationships between free
466 // regions, until regionck, as described in #3238.
468 fn visit_fn(&mut self, _fk
: intravisit
::FnKind
<'v
>, fd
: &'v hir
::FnDecl
,
469 b
: &'v hir
::Block
, span
: Span
, id
: ast
::NodeId
) {
470 self.visit_fn_body(id
, fd
, b
, span
)
473 fn visit_expr(&mut self, ex
: &hir
::Expr
) { visit_expr(self, ex); }
475 //visit_pat: visit_pat, // (..) see above
477 fn visit_arm(&mut self, a
: &hir
::Arm
) { visit_arm(self, a); }
479 fn visit_local(&mut self, l
: &hir
::Local
) { visit_local(self, l); }
481 fn visit_block(&mut self, b
: &hir
::Block
) { visit_block(self, b); }
484 fn visit_block(rcx
: &mut Rcx
, b
: &hir
::Block
) {
485 intravisit
::walk_block(rcx
, b
);
488 fn visit_arm(rcx
: &mut Rcx
, arm
: &hir
::Arm
) {
491 constrain_bindings_in_pat(&p
, rcx
);
494 intravisit
::walk_arm(rcx
, arm
);
497 fn visit_local(rcx
: &mut Rcx
, l
: &hir
::Local
) {
499 constrain_bindings_in_pat(&l
.pat
, rcx
);
501 intravisit
::walk_local(rcx
, l
);
504 fn constrain_bindings_in_pat(pat
: &hir
::Pat
, rcx
: &mut Rcx
) {
505 let tcx
= rcx
.fcx
.tcx();
506 debug
!("regionck::visit_pat(pat={:?})", pat
);
507 pat_util
::pat_bindings(&tcx
.def_map
, pat
, |_
, id
, span
, _
| {
508 // If we have a variable that contains region'd data, that
509 // data will be accessible from anywhere that the variable is
510 // accessed. We must be wary of loops like this:
512 // // from src/test/compile-fail/borrowck-lend-flow.rs
513 // let mut v = box 3, w = box 4;
514 // let mut x = &mut w;
517 // borrow(v); //~ ERROR cannot borrow
518 // x = &mut v; // (1)
521 // Typically, we try to determine the region of a borrow from
522 // those points where it is dereferenced. In this case, one
523 // might imagine that the lifetime of `x` need only be the
524 // body of the loop. But of course this is incorrect because
525 // the pointer that is created at point (1) is consumed at
526 // point (2), meaning that it must be live across the loop
527 // iteration. The easiest way to guarantee this is to require
528 // that the lifetime of any regions that appear in a
529 // variable's type enclose at least the variable's scope.
531 let var_scope
= tcx
.region_maps
.var_scope(id
);
533 let origin
= infer
::BindingTypeIsNotValidAtDecl(span
);
534 type_of_node_must_outlive(rcx
, origin
, id
, ty
::ReScope(var_scope
));
536 let typ
= rcx
.resolve_node_type(id
);
537 dropck
::check_safety_of_destructor_if_necessary(rcx
, typ
, span
, var_scope
);
541 fn visit_expr(rcx
: &mut Rcx
, expr
: &hir
::Expr
) {
542 debug
!("regionck::visit_expr(e={:?}, repeating_scope={})",
543 expr
, rcx
.repeating_scope
);
545 // No matter what, the type of each expression must outlive the
546 // scope of that expression. This also guarantees basic WF.
547 let expr_ty
= rcx
.resolve_node_type(expr
.id
);
548 // the region corresponding to this expression
549 let expr_region
= ty
::ReScope(rcx
.tcx().region_maps
.node_extent(expr
.id
));
550 type_must_outlive(rcx
, infer
::ExprTypeIsNotInScope(expr_ty
, expr
.span
),
551 expr_ty
, expr_region
);
553 let method_call
= MethodCall
::expr(expr
.id
);
554 let opt_method_callee
= rcx
.fcx
.inh
.tables
.borrow().method_map
.get(&method_call
).cloned();
555 let has_method_map
= opt_method_callee
.is_some();
557 // If we are calling a method (either explicitly or via an
558 // overloaded operator), check that all of the types provided as
559 // arguments for its type parameters are well-formed, and all the regions
560 // provided as arguments outlive the call.
561 if let Some(callee
) = opt_method_callee
{
562 let origin
= match expr
.node
{
563 hir
::ExprMethodCall(..) =>
564 infer
::ParameterOrigin
::MethodCall
,
565 hir
::ExprUnary(op
, _
) if op
== hir
::UnDeref
=>
566 infer
::ParameterOrigin
::OverloadedDeref
,
568 infer
::ParameterOrigin
::OverloadedOperator
571 substs_wf_in_scope(rcx
, origin
, &callee
.substs
, expr
.span
, expr_region
);
572 type_must_outlive(rcx
, infer
::ExprTypeIsNotInScope(callee
.ty
, expr
.span
),
573 callee
.ty
, expr_region
);
576 // Check any autoderefs or autorefs that appear.
577 let adjustment
= rcx
.fcx
.inh
.tables
.borrow().adjustments
.get(&expr
.id
).map(|a
| a
.clone());
578 if let Some(adjustment
) = adjustment
{
579 debug
!("adjustment={:?}", adjustment
);
581 adjustment
::AdjustDerefRef(adjustment
::AutoDerefRef
{
582 autoderefs
, ref autoref
, ..
584 let expr_ty
= rcx
.resolve_node_type(expr
.id
);
585 constrain_autoderefs(rcx
, expr
, autoderefs
, expr_ty
);
586 if let Some(ref autoref
) = *autoref
{
587 link_autoref(rcx
, expr
, autoderefs
, autoref
);
589 // Require that the resulting region encompasses
592 // FIXME(#6268) remove to support nested method calls
593 type_of_node_must_outlive(
594 rcx
, infer
::AutoBorrow(expr
.span
),
595 expr
.id
, expr_region
);
599 adjustment::AutoObject(_, ref bounds, _, _) => {
600 // Determine if we are casting `expr` to a trait
601 // instance. If so, we have to be sure that the type
602 // of the source obeys the new region bound.
603 let source_ty = rcx.resolve_node_type(expr.id);
604 type_must_outlive(rcx, infer::RelateObjectBound(expr.span),
605 source_ty, bounds.region_bound);
611 // If necessary, constrain destructors in the unadjusted form of this
614 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
.infcx());
615 mc
.cat_expr_unadjusted(expr
)
619 check_safety_of_rvalue_destructor_if_necessary(rcx
,
624 let tcx
= rcx
.fcx
.tcx();
625 tcx
.sess
.delay_span_bug(expr
.span
, "cat_expr_unadjusted Errd");
630 // If necessary, constrain destructors in this expression. This will be
631 // the adjusted form if there is an adjustment.
633 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
.infcx());
638 check_safety_of_rvalue_destructor_if_necessary(rcx
, head_cmt
, expr
.span
);
641 let tcx
= rcx
.fcx
.tcx();
642 tcx
.sess
.delay_span_bug(expr
.span
, "cat_expr Errd");
646 debug
!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
647 expr
, rcx
.repeating_scope
);
649 hir
::ExprPath(..) => {
650 rcx
.fcx
.opt_node_ty_substs(expr
.id
, |item_substs
| {
651 let origin
= infer
::ParameterOrigin
::Path
;
652 substs_wf_in_scope(rcx
, origin
, &item_substs
.substs
, expr
.span
, expr_region
);
656 hir
::ExprCall(ref callee
, ref args
) => {
658 constrain_call(rcx
, expr
, Some(&callee
),
659 args
.iter().map(|e
| &**e
), false);
661 constrain_callee(rcx
, callee
.id
, expr
, &callee
);
662 constrain_call(rcx
, expr
, None
,
663 args
.iter().map(|e
| &**e
), false);
666 intravisit
::walk_expr(rcx
, expr
);
669 hir
::ExprMethodCall(_
, _
, ref args
) => {
670 constrain_call(rcx
, expr
, Some(&args
[0]),
671 args
[1..].iter().map(|e
| &**e
), false);
673 intravisit
::walk_expr(rcx
, expr
);
676 hir
::ExprAssignOp(_
, ref lhs
, ref rhs
) => {
678 constrain_call(rcx
, expr
, Some(&lhs
),
679 Some(&**rhs
).into_iter(), false);
682 intravisit
::walk_expr(rcx
, expr
);
685 hir
::ExprIndex(ref lhs
, ref rhs
) if has_method_map
=> {
686 constrain_call(rcx
, expr
, Some(&lhs
),
687 Some(&**rhs
).into_iter(), true);
689 intravisit
::walk_expr(rcx
, expr
);
692 hir
::ExprBinary(op
, ref lhs
, ref rhs
) if has_method_map
=> {
693 let implicitly_ref_args
= !hir_util
::is_by_value_binop(op
.node
);
695 // As `expr_method_call`, but the call is via an
696 // overloaded op. Note that we (sadly) currently use an
697 // implicit "by ref" sort of passing style here. This
698 // should be converted to an adjustment!
699 constrain_call(rcx
, expr
, Some(&lhs
),
700 Some(&**rhs
).into_iter(), implicitly_ref_args
);
702 intravisit
::walk_expr(rcx
, expr
);
705 hir
::ExprBinary(_
, ref lhs
, ref rhs
) => {
706 // If you do `x OP y`, then the types of `x` and `y` must
707 // outlive the operation you are performing.
708 let lhs_ty
= rcx
.resolve_expr_type_adjusted(&lhs
);
709 let rhs_ty
= rcx
.resolve_expr_type_adjusted(&rhs
);
710 for &ty
in &[lhs_ty
, rhs_ty
] {
711 type_must_outlive(rcx
,
712 infer
::Operand(expr
.span
),
716 intravisit
::walk_expr(rcx
, expr
);
719 hir
::ExprUnary(op
, ref lhs
) if has_method_map
=> {
720 let implicitly_ref_args
= !hir_util
::is_by_value_unop(op
);
723 constrain_call(rcx
, expr
, Some(&lhs
),
724 None
::<hir
::Expr
>.iter(), implicitly_ref_args
);
726 intravisit
::walk_expr(rcx
, expr
);
729 hir
::ExprUnary(hir
::UnDeref
, ref base
) => {
730 // For *a, the lifetime of a must enclose the deref
731 let method_call
= MethodCall
::expr(expr
.id
);
732 let base_ty
= match rcx
.fcx
.inh
.tables
.borrow().method_map
.get(&method_call
) {
734 constrain_call(rcx
, expr
, Some(&base
),
735 None
::<hir
::Expr
>.iter(), true);
736 let fn_ret
= // late-bound regions in overloaded method calls are instantiated
737 rcx
.tcx().no_late_bound_regions(&method
.ty
.fn_ret()).unwrap();
740 None
=> rcx
.resolve_node_type(base
.id
)
742 if let ty
::TyRef(r_ptr
, _
) = base_ty
.sty
{
743 mk_subregion_due_to_dereference(
744 rcx
, expr
.span
, expr_region
, *r_ptr
);
747 intravisit
::walk_expr(rcx
, expr
);
750 hir
::ExprIndex(ref vec_expr
, _
) => {
751 // For a[b], the lifetime of a must enclose the deref
752 let vec_type
= rcx
.resolve_expr_type_adjusted(&vec_expr
);
753 constrain_index(rcx
, expr
, vec_type
);
755 intravisit
::walk_expr(rcx
, expr
);
758 hir
::ExprCast(ref source
, _
) => {
759 // Determine if we are casting `source` to a trait
760 // instance. If so, we have to be sure that the type of
761 // the source obeys the trait's region bound.
762 constrain_cast(rcx
, expr
, &source
);
763 intravisit
::walk_expr(rcx
, expr
);
766 hir
::ExprAddrOf(m
, ref base
) => {
767 link_addr_of(rcx
, expr
, m
, &base
);
769 // Require that when you write a `&expr` expression, the
770 // resulting pointer has a lifetime that encompasses the
771 // `&expr` expression itself. Note that we constraining
772 // the type of the node expr.id here *before applying
775 // FIXME(#6268) nested method calls requires that this rule change
776 let ty0
= rcx
.resolve_node_type(expr
.id
);
777 type_must_outlive(rcx
, infer
::AddrOf(expr
.span
), ty0
, expr_region
);
778 intravisit
::walk_expr(rcx
, expr
);
781 hir
::ExprMatch(ref discr
, ref arms
, _
) => {
782 link_match(rcx
, &discr
, &arms
[..]);
784 intravisit
::walk_expr(rcx
, expr
);
787 hir
::ExprClosure(_
, _
, ref body
) => {
788 check_expr_fn_block(rcx
, expr
, &body
);
791 hir
::ExprLoop(ref body
, _
) => {
792 let repeating_scope
= rcx
.set_repeating_scope(body
.id
);
793 intravisit
::walk_expr(rcx
, expr
);
794 rcx
.set_repeating_scope(repeating_scope
);
797 hir
::ExprWhile(ref cond
, ref body
, _
) => {
798 let repeating_scope
= rcx
.set_repeating_scope(cond
.id
);
799 rcx
.visit_expr(&cond
);
801 rcx
.set_repeating_scope(body
.id
);
802 rcx
.visit_block(&body
);
804 rcx
.set_repeating_scope(repeating_scope
);
807 hir
::ExprRet(Some(ref ret_expr
)) => {
808 let call_site_scope
= rcx
.call_site_scope
;
809 debug
!("visit_expr ExprRet ret_expr.id {} call_site_scope: {:?}",
810 ret_expr
.id
, call_site_scope
);
811 type_of_node_must_outlive(rcx
,
812 infer
::CallReturn(ret_expr
.span
),
814 ty
::ReScope(call_site_scope
.unwrap()));
815 intravisit
::walk_expr(rcx
, expr
);
819 intravisit
::walk_expr(rcx
, expr
);
824 fn constrain_cast(rcx
: &mut Rcx
,
825 cast_expr
: &hir
::Expr
,
826 source_expr
: &hir
::Expr
)
828 debug
!("constrain_cast(cast_expr={:?}, source_expr={:?})",
832 let source_ty
= rcx
.resolve_node_type(source_expr
.id
);
833 let target_ty
= rcx
.resolve_node_type(cast_expr
.id
);
835 walk_cast(rcx
, cast_expr
, source_ty
, target_ty
);
837 fn walk_cast
<'a
, 'tcx
>(rcx
: &mut Rcx
<'a
, 'tcx
>,
838 cast_expr
: &hir
::Expr
,
841 debug
!("walk_cast(from_ty={:?}, to_ty={:?})",
844 match (&from_ty
.sty
, &to_ty
.sty
) {
845 /*From:*/ (&ty
::TyRef(from_r
, ref from_mt
),
846 /*To: */ &ty
::TyRef(to_r
, ref to_mt
)) => {
847 // Target cannot outlive source, naturally.
848 rcx
.fcx
.mk_subr(infer
::Reborrow(cast_expr
.span
), *to_r
, *from_r
);
849 walk_cast(rcx
, cast_expr
, from_mt
.ty
, to_mt
.ty
);
853 /*To: */ &ty
::TyTrait(box ty
::TraitTy { ref bounds, .. }
)) => {
854 // When T is existentially quantified as a trait
855 // `Foo+'to`, it must outlive the region bound `'to`.
856 type_must_outlive(rcx
, infer
::RelateObjectBound(cast_expr
.span
),
857 from_ty
, bounds
.region_bound
);
860 /*From:*/ (&ty
::TyBox(from_referent_ty
),
861 /*To: */ &ty
::TyBox(to_referent_ty
)) => {
862 walk_cast(rcx
, cast_expr
, from_referent_ty
, to_referent_ty
);
870 fn check_expr_fn_block(rcx
: &mut Rcx
,
873 let repeating_scope
= rcx
.set_repeating_scope(body
.id
);
874 intravisit
::walk_expr(rcx
, expr
);
875 rcx
.set_repeating_scope(repeating_scope
);
878 fn constrain_callee(rcx
: &mut Rcx
,
879 callee_id
: ast
::NodeId
,
880 _call_expr
: &hir
::Expr
,
881 _callee_expr
: &hir
::Expr
) {
882 let callee_ty
= rcx
.resolve_node_type(callee_id
);
883 match callee_ty
.sty
{
884 ty
::TyBareFn(..) => { }
886 // this should not happen, but it does if the program is
889 // tcx.sess.span_bug(
891 // format!("Calling non-function: {}", callee_ty));
896 fn constrain_call
<'a
, I
: Iterator
<Item
=&'a hir
::Expr
>>(rcx
: &mut Rcx
,
897 call_expr
: &hir
::Expr
,
898 receiver
: Option
<&hir
::Expr
>,
900 implicitly_ref_args
: bool
) {
901 //! Invoked on every call site (i.e., normal calls, method calls,
902 //! and overloaded operators). Constrains the regions which appear
903 //! in the type of the function. Also constrains the regions that
904 //! appear in the arguments appropriately.
906 debug
!("constrain_call(call_expr={:?}, \
908 implicitly_ref_args={})",
911 implicitly_ref_args
);
913 // `callee_region` is the scope representing the time in which the
916 // FIXME(#6268) to support nested method calls, should be callee_id
917 let callee_scope
= rcx
.tcx().region_maps
.node_extent(call_expr
.id
);
918 let callee_region
= ty
::ReScope(callee_scope
);
920 debug
!("callee_region={:?}", callee_region
);
922 for arg_expr
in arg_exprs
{
923 debug
!("Argument: {:?}", arg_expr
);
925 // ensure that any regions appearing in the argument type are
926 // valid for at least the lifetime of the function:
927 type_of_node_must_outlive(
928 rcx
, infer
::CallArg(arg_expr
.span
),
929 arg_expr
.id
, callee_region
);
931 // unfortunately, there are two means of taking implicit
932 // references, and we need to propagate constraints as a
933 // result. modes are going away and the "DerefArgs" code
934 // should be ported to use adjustments
935 if implicitly_ref_args
{
936 link_by_ref(rcx
, arg_expr
, callee_scope
);
940 // as loop above, but for receiver
941 if let Some(r
) = receiver
{
942 debug
!("receiver: {:?}", r
);
943 type_of_node_must_outlive(
944 rcx
, infer
::CallRcvr(r
.span
),
945 r
.id
, callee_region
);
946 if implicitly_ref_args
{
947 link_by_ref(rcx
, &r
, callee_scope
);
952 /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being
953 /// dereferenced, the lifetime of the pointer includes the deref expr.
954 fn constrain_autoderefs
<'a
, 'tcx
>(rcx
: &mut Rcx
<'a
, 'tcx
>,
955 deref_expr
: &hir
::Expr
,
957 mut derefd_ty
: Ty
<'tcx
>)
959 debug
!("constrain_autoderefs(deref_expr={:?}, derefs={}, derefd_ty={:?})",
964 let s_deref_expr
= rcx
.tcx().region_maps
.node_extent(deref_expr
.id
);
965 let r_deref_expr
= ty
::ReScope(s_deref_expr
);
967 let method_call
= MethodCall
::autoderef(deref_expr
.id
, i
as u32);
968 debug
!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call
, derefs
);
970 let method
= rcx
.fcx
.inh
.tables
.borrow().method_map
.get(&method_call
).map(|m
| m
.clone());
972 derefd_ty
= match method
{
974 debug
!("constrain_autoderefs: #{} is overloaded, method={:?}",
977 let origin
= infer
::ParameterOrigin
::OverloadedDeref
;
978 substs_wf_in_scope(rcx
, origin
, method
.substs
, deref_expr
.span
, r_deref_expr
);
980 // Treat overloaded autoderefs as if an AutoRef adjustment
981 // was applied on the base type, as that is always the case.
982 let fn_sig
= method
.ty
.fn_sig();
983 let fn_sig
= // late-bound regions should have been instantiated
984 rcx
.tcx().no_late_bound_regions(fn_sig
).unwrap();
985 let self_ty
= fn_sig
.inputs
[0];
986 let (m
, r
) = match self_ty
.sty
{
987 ty
::TyRef(r
, ref m
) => (m
.mutbl
, r
),
989 rcx
.tcx().sess
.span_bug(
991 &format
!("bad overloaded deref type {:?}",
996 debug
!("constrain_autoderefs: receiver r={:?} m={:?}",
1000 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
.infcx());
1001 let self_cmt
= ignore_err
!(mc
.cat_expr_autoderefd(deref_expr
, i
));
1002 debug
!("constrain_autoderefs: self_cmt={:?}",
1004 link_region(rcx
, deref_expr
.span
, r
,
1005 ty
::BorrowKind
::from_mutbl(m
), self_cmt
);
1008 // Specialized version of constrain_call.
1009 type_must_outlive(rcx
, infer
::CallRcvr(deref_expr
.span
),
1010 self_ty
, r_deref_expr
);
1011 match fn_sig
.output
{
1012 ty
::FnConverging(return_type
) => {
1013 type_must_outlive(rcx
, infer
::CallReturn(deref_expr
.span
),
1014 return_type
, r_deref_expr
);
1017 ty
::FnDiverging
=> unreachable
!()
1023 if let ty
::TyRef(r_ptr
, _
) = derefd_ty
.sty
{
1024 mk_subregion_due_to_dereference(rcx
, deref_expr
.span
,
1025 r_deref_expr
, *r_ptr
);
1028 match derefd_ty
.builtin_deref(true, ty
::NoPreference
) {
1029 Some(mt
) => derefd_ty
= mt
.ty
,
1030 /* if this type can't be dereferenced, then there's already an error
1031 in the session saying so. Just bail out for now */
1037 pub fn mk_subregion_due_to_dereference(rcx
: &mut Rcx
,
1039 minimum_lifetime
: ty
::Region
,
1040 maximum_lifetime
: ty
::Region
) {
1041 rcx
.fcx
.mk_subr(infer
::DerefPointer(deref_span
),
1042 minimum_lifetime
, maximum_lifetime
)
1045 fn check_safety_of_rvalue_destructor_if_necessary
<'a
, 'tcx
>(rcx
: &mut Rcx
<'a
, 'tcx
>,
1049 Categorization
::Rvalue(region
) => {
1051 ty
::ReScope(rvalue_scope
) => {
1052 let typ
= rcx
.resolve_type(cmt
.ty
);
1053 dropck
::check_safety_of_destructor_if_necessary(rcx
,
1063 &format
!("unexpected rvalue region in rvalue \
1064 destructor safety checking: `{:?}`",
1073 /// Invoked on any index expression that occurs. Checks that if this is a slice being indexed, the
1074 /// lifetime of the pointer includes the deref expr.
1075 fn constrain_index
<'a
, 'tcx
>(rcx
: &mut Rcx
<'a
, 'tcx
>,
1076 index_expr
: &hir
::Expr
,
1077 indexed_ty
: Ty
<'tcx
>)
1079 debug
!("constrain_index(index_expr=?, indexed_ty={}",
1080 rcx
.fcx
.infcx().ty_to_string(indexed_ty
));
1082 let r_index_expr
= ty
::ReScope(rcx
.tcx().region_maps
.node_extent(index_expr
.id
));
1083 if let ty
::TyRef(r_ptr
, mt
) = indexed_ty
.sty
{
1085 ty
::TySlice(_
) | ty
::TyStr
=> {
1086 rcx
.fcx
.mk_subr(infer
::IndexSlice(index_expr
.span
),
1087 r_index_expr
, *r_ptr
);
1094 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1095 /// adjustments) are valid for at least `minimum_lifetime`
1096 fn type_of_node_must_outlive
<'a
, 'tcx
>(
1097 rcx
: &mut Rcx
<'a
, 'tcx
>,
1098 origin
: infer
::SubregionOrigin
<'tcx
>,
1100 minimum_lifetime
: ty
::Region
)
1102 let tcx
= rcx
.fcx
.tcx();
1104 // Try to resolve the type. If we encounter an error, then typeck
1105 // is going to fail anyway, so just stop here and let typeck
1106 // report errors later on in the writeback phase.
1107 let ty0
= rcx
.resolve_node_type(id
);
1108 let ty
= ty0
.adjust(tcx
, origin
.span(), id
,
1109 rcx
.fcx
.inh
.tables
.borrow().adjustments
.get(&id
),
1110 |method_call
| rcx
.resolve_method_type(method_call
));
1111 debug
!("constrain_regions_in_type_of_node(\
1112 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
1114 id
, minimum_lifetime
);
1115 type_must_outlive(rcx
, origin
, ty
, minimum_lifetime
);
1118 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1119 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1120 fn link_addr_of(rcx
: &mut Rcx
, expr
: &hir
::Expr
,
1121 mutability
: hir
::Mutability
, base
: &hir
::Expr
) {
1122 debug
!("link_addr_of(expr={:?}, base={:?})", expr
, base
);
1125 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
.infcx());
1126 ignore_err
!(mc
.cat_expr(base
))
1129 debug
!("link_addr_of: cmt={:?}", cmt
);
1131 link_region_from_node_type(rcx
, expr
.span
, expr
.id
, mutability
, cmt
);
1134 /// Computes the guarantors for any ref bindings in a `let` and
1135 /// then ensures that the lifetime of the resulting pointer is
1136 /// linked to the lifetime of the initialization expression.
1137 fn link_local(rcx
: &Rcx
, local
: &hir
::Local
) {
1138 debug
!("regionck::for_local()");
1139 let init_expr
= match local
.init
{
1141 Some(ref expr
) => &**expr
,
1143 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
.infcx());
1144 let discr_cmt
= ignore_err
!(mc
.cat_expr(init_expr
));
1145 link_pattern(rcx
, mc
, discr_cmt
, &local
.pat
);
1148 /// Computes the guarantors for any ref bindings in a match and
1149 /// then ensures that the lifetime of the resulting pointer is
1150 /// linked to the lifetime of its guarantor (if any).
1151 fn link_match(rcx
: &Rcx
, discr
: &hir
::Expr
, arms
: &[hir
::Arm
]) {
1152 debug
!("regionck::for_match()");
1153 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
.infcx());
1154 let discr_cmt
= ignore_err
!(mc
.cat_expr(discr
));
1155 debug
!("discr_cmt={:?}", discr_cmt
);
1157 for root_pat
in &arm
.pats
{
1158 link_pattern(rcx
, mc
, discr_cmt
.clone(), &root_pat
);
1163 /// Computes the guarantors for any ref bindings in a match and
1164 /// then ensures that the lifetime of the resulting pointer is
1165 /// linked to the lifetime of its guarantor (if any).
1166 fn link_fn_args(rcx
: &Rcx
, body_scope
: CodeExtent
, args
: &[hir
::Arg
]) {
1167 debug
!("regionck::link_fn_args(body_scope={:?})", body_scope
);
1168 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
.infcx());
1170 let arg_ty
= rcx
.fcx
.node_ty(arg
.id
);
1171 let re_scope
= ty
::ReScope(body_scope
);
1172 let arg_cmt
= mc
.cat_rvalue(arg
.id
, arg
.ty
.span
, re_scope
, arg_ty
);
1173 debug
!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1177 link_pattern(rcx
, mc
, arg_cmt
, &arg
.pat
);
1181 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found in the discriminant, if
1183 fn link_pattern
<'t
, 'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1184 mc
: mc
::MemCategorizationContext
<'t
, 'a
, 'tcx
>,
1185 discr_cmt
: mc
::cmt
<'tcx
>,
1186 root_pat
: &hir
::Pat
) {
1187 debug
!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1190 let _
= mc
.cat_pattern(discr_cmt
, root_pat
, |mc
, sub_cmt
, sub_pat
| {
1191 match sub_pat
.node
{
1193 PatKind
::Ident(hir
::BindByRef(mutbl
), _
, _
) => {
1194 link_region_from_node_type(
1195 rcx
, sub_pat
.span
, sub_pat
.id
,
1199 // `[_, ..slice, _]` pattern
1200 PatKind
::Vec(_
, Some(ref slice_pat
), _
) => {
1201 match mc
.cat_slice_pattern(sub_cmt
, &slice_pat
) {
1202 Ok((slice_cmt
, slice_mutbl
, slice_r
)) => {
1203 link_region(rcx
, sub_pat
.span
, &slice_r
,
1204 ty
::BorrowKind
::from_mutbl(slice_mutbl
),
1215 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1217 fn link_autoref(rcx
: &Rcx
,
1220 autoref
: &adjustment
::AutoRef
)
1222 debug
!("link_autoref(autoref={:?})", autoref
);
1223 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
.infcx());
1224 let expr_cmt
= ignore_err
!(mc
.cat_expr_autoderefd(expr
, autoderefs
));
1225 debug
!("expr_cmt={:?}", expr_cmt
);
1228 adjustment
::AutoPtr(r
, m
) => {
1229 link_region(rcx
, expr
.span
, r
,
1230 ty
::BorrowKind
::from_mutbl(m
), expr_cmt
);
1233 adjustment
::AutoUnsafe(m
) => {
1234 let r
= ty
::ReScope(rcx
.tcx().region_maps
.node_extent(expr
.id
));
1235 link_region(rcx
, expr
.span
, &r
, ty
::BorrowKind
::from_mutbl(m
), expr_cmt
);
1240 /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and
1241 /// must outlive `callee_scope`.
1242 fn link_by_ref(rcx
: &Rcx
,
1244 callee_scope
: CodeExtent
) {
1245 debug
!("link_by_ref(expr={:?}, callee_scope={:?})",
1246 expr
, callee_scope
);
1247 let mc
= mc
::MemCategorizationContext
::new(rcx
.fcx
.infcx());
1248 let expr_cmt
= ignore_err
!(mc
.cat_expr(expr
));
1249 let borrow_region
= ty
::ReScope(callee_scope
);
1250 link_region(rcx
, expr
.span
, &borrow_region
, ty
::ImmBorrow
, expr_cmt
);
1253 /// Like `link_region()`, except that the region is extracted from the type of `id`, which must be
1254 /// some reference (`&T`, `&str`, etc).
1255 fn link_region_from_node_type
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1258 mutbl
: hir
::Mutability
,
1259 cmt_borrowed
: mc
::cmt
<'tcx
>) {
1260 debug
!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1261 id
, mutbl
, cmt_borrowed
);
1263 let rptr_ty
= rcx
.resolve_node_type(id
);
1264 if let ty
::TyRef(&r
, _
) = rptr_ty
.sty
{
1265 debug
!("rptr_ty={}", rptr_ty
);
1266 link_region(rcx
, span
, &r
, ty
::BorrowKind
::from_mutbl(mutbl
),
1271 /// Informs the inference engine that `borrow_cmt` is being borrowed with kind `borrow_kind` and
1272 /// lifetime `borrow_region`. In order to ensure borrowck is satisfied, this may create constraints
1273 /// between regions, as explained in `link_reborrowed_region()`.
1274 fn link_region
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1276 borrow_region
: &ty
::Region
,
1277 borrow_kind
: ty
::BorrowKind
,
1278 borrow_cmt
: mc
::cmt
<'tcx
>) {
1279 let mut borrow_cmt
= borrow_cmt
;
1280 let mut borrow_kind
= borrow_kind
;
1282 let origin
= infer
::DataBorrowed(borrow_cmt
.ty
, span
);
1283 type_must_outlive(rcx
, origin
, borrow_cmt
.ty
, *borrow_region
);
1286 debug
!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1290 match borrow_cmt
.cat
.clone() {
1291 Categorization
::Deref(ref_cmt
, _
,
1292 mc
::Implicit(ref_kind
, ref_region
)) |
1293 Categorization
::Deref(ref_cmt
, _
,
1294 mc
::BorrowedPtr(ref_kind
, ref_region
)) => {
1295 match link_reborrowed_region(rcx
, span
,
1296 borrow_region
, borrow_kind
,
1297 ref_cmt
, ref_region
, ref_kind
,
1309 Categorization
::Downcast(cmt_base
, _
) |
1310 Categorization
::Deref(cmt_base
, _
, mc
::Unique
) |
1311 Categorization
::Interior(cmt_base
, _
) => {
1312 // Borrowing interior or owned data requires the base
1313 // to be valid and borrowable in the same fashion.
1314 borrow_cmt
= cmt_base
;
1315 borrow_kind
= borrow_kind
;
1318 Categorization
::Deref(_
, _
, mc
::UnsafePtr(..)) |
1319 Categorization
::StaticItem
|
1320 Categorization
::Upvar(..) |
1321 Categorization
::Local(..) |
1322 Categorization
::Rvalue(..) => {
1323 // These are all "base cases" with independent lifetimes
1324 // that are not subject to inference
1331 /// This is the most complicated case: the path being borrowed is
1332 /// itself the referent of a borrowed pointer. Let me give an
1333 /// example fragment of code to make clear(er) the situation:
1335 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1337 /// &'z *r // the reborrow has lifetime 'z
1339 /// Now, in this case, our primary job is to add the inference
1340 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1341 /// parameters in (roughly) terms of the example:
1343 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1344 /// borrow_region ^~ ref_region ^~
1345 /// borrow_kind ^~ ref_kind ^~
1348 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1350 /// Unfortunately, there are some complications beyond the simple
1351 /// scenario I just painted:
1353 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1354 /// case, we have two jobs. First, we are inferring whether this reference
1355 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1356 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1357 /// then `r` must be an `&mut` reference). Second, whenever we link
1358 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1359 /// case we adjust the cause to indicate that the reference being
1360 /// "reborrowed" is itself an upvar. This provides a nicer error message
1361 /// should something go wrong.
1363 /// 2. There may in fact be more levels of reborrowing. In the
1364 /// example, I said the borrow was like `&'z *r`, but it might
1365 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1366 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1367 /// and `'z <= 'b`. This is explained more below.
1369 /// The return value of this function indicates whether we need to
1370 /// recurse and process `ref_cmt` (see case 2 above).
1371 fn link_reborrowed_region
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1373 borrow_region
: &ty
::Region
,
1374 borrow_kind
: ty
::BorrowKind
,
1375 ref_cmt
: mc
::cmt
<'tcx
>,
1376 ref_region
: ty
::Region
,
1377 mut ref_kind
: ty
::BorrowKind
,
1379 -> Option
<(mc
::cmt
<'tcx
>, ty
::BorrowKind
)>
1381 // Possible upvar ID we may need later to create an entry in the
1384 // Detect by-ref upvar `x`:
1385 let cause
= match note
{
1386 mc
::NoteUpvarRef(ref upvar_id
) => {
1387 let upvar_capture_map
= &rcx
.fcx
.inh
.tables
.borrow_mut().upvar_capture_map
;
1388 match upvar_capture_map
.get(upvar_id
) {
1389 Some(&ty
::UpvarCapture
::ByRef(ref upvar_borrow
)) => {
1390 // The mutability of the upvar may have been modified
1391 // by the above adjustment, so update our local variable.
1392 ref_kind
= upvar_borrow
.kind
;
1394 infer
::ReborrowUpvar(span
, *upvar_id
)
1397 rcx
.tcx().sess
.span_bug(
1399 &format
!("Illegal upvar id: {:?}",
1404 mc
::NoteClosureEnv(ref upvar_id
) => {
1405 // We don't have any mutability changes to propagate, but
1406 // we do want to note that an upvar reborrow caused this
1408 infer
::ReborrowUpvar(span
, *upvar_id
)
1411 infer
::Reborrow(span
)
1415 debug
!("link_reborrowed_region: {:?} <= {:?}",
1418 rcx
.fcx
.mk_subr(cause
, *borrow_region
, ref_region
);
1420 // If we end up needing to recurse and establish a region link
1421 // with `ref_cmt`, calculate what borrow kind we will end up
1422 // needing. This will be used below.
1424 // One interesting twist is that we can weaken the borrow kind
1425 // when we recurse: to reborrow an `&mut` referent as mutable,
1426 // borrowck requires a unique path to the `&mut` reference but not
1427 // necessarily a *mutable* path.
1428 let new_borrow_kind
= match borrow_kind
{
1431 ty
::MutBorrow
| ty
::UniqueImmBorrow
=>
1435 // Decide whether we need to recurse and link any regions within
1436 // the `ref_cmt`. This is concerned for the case where the value
1437 // being reborrowed is in fact a borrowed pointer found within
1438 // another borrowed pointer. For example:
1440 // let p: &'b &'a mut T = ...;
1444 // What makes this case particularly tricky is that, if the data
1445 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1446 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1447 // (otherwise the user might mutate through the `&mut T` reference
1448 // after `'b` expires and invalidate the borrow we are looking at
1451 // So let's re-examine our parameters in light of this more
1452 // complicated (possible) scenario:
1454 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1455 // borrow_region ^~ ref_region ^~
1456 // borrow_kind ^~ ref_kind ^~
1459 // (Note that since we have not examined `ref_cmt.cat`, we don't
1460 // know whether this scenario has occurred; but I wanted to show
1461 // how all the types get adjusted.)
1464 // The reference being reborrowed is a sharable ref of
1465 // type `&'a T`. In this case, it doesn't matter where we
1466 // *found* the `&T` pointer, the memory it references will
1467 // be valid and immutable for `'a`. So we can stop here.
1469 // (Note that the `borrow_kind` must also be ImmBorrow or
1470 // else the user is borrowed imm memory as mut memory,
1471 // which means they'll get an error downstream in borrowck
1476 ty
::MutBorrow
| ty
::UniqueImmBorrow
=> {
1477 // The reference being reborrowed is either an `&mut T` or
1478 // `&uniq T`. This is the case where recursion is needed.
1479 return Some((ref_cmt
, new_borrow_kind
));
1484 /// Checks that the values provided for type/region arguments in a given
1485 /// expression are well-formed and in-scope.
1486 pub fn substs_wf_in_scope
<'a
,'tcx
>(rcx
: &mut Rcx
<'a
,'tcx
>,
1487 origin
: infer
::ParameterOrigin
,
1488 substs
: &Substs
<'tcx
>,
1490 expr_region
: ty
::Region
) {
1491 debug
!("substs_wf_in_scope(substs={:?}, \
1495 substs
, expr_region
, origin
, expr_span
);
1497 let origin
= infer
::ParameterInScope(origin
, expr_span
);
1499 for ®ion
in substs
.regions() {
1500 rcx
.fcx
.mk_subr(origin
.clone(), expr_region
, region
);
1503 for &ty
in &substs
.types
{
1504 let ty
= rcx
.resolve_type(ty
);
1505 type_must_outlive(rcx
, origin
.clone(), ty
, expr_region
);
1509 /// Ensures that type is well-formed in `region`, which implies (among
1510 /// other things) that all borrowed data reachable via `ty` outlives
1512 pub fn type_must_outlive
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1513 origin
: infer
::SubregionOrigin
<'tcx
>,
1517 let ty
= rcx
.resolve_type(ty
);
1519 debug
!("type_must_outlive(ty={:?}, region={:?}, origin={:?})",
1524 assert
!(!ty
.has_escaping_regions());
1526 let components
= ty
::outlives
::components(rcx
.infcx(), ty
);
1527 components_must_outlive(rcx
, origin
, components
, region
);
1530 fn components_must_outlive
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1531 origin
: infer
::SubregionOrigin
<'tcx
>,
1532 components
: Vec
<ty
::outlives
::Component
<'tcx
>>,
1535 for component
in components
{
1536 let origin
= origin
.clone();
1538 ty
::outlives
::Component
::Region(region1
) => {
1539 rcx
.fcx
.mk_subr(origin
, region
, region1
);
1541 ty
::outlives
::Component
::Param(param_ty
) => {
1542 param_ty_must_outlive(rcx
, origin
, region
, param_ty
);
1544 ty
::outlives
::Component
::Projection(projection_ty
) => {
1545 projection_must_outlive(rcx
, origin
, region
, projection_ty
);
1547 ty
::outlives
::Component
::EscapingProjection(subcomponents
) => {
1548 components_must_outlive(rcx
, origin
, subcomponents
, region
);
1550 ty
::outlives
::Component
::UnresolvedInferenceVariable(v
) => {
1551 // ignore this, we presume it will yield an error
1552 // later, since if a type variable is not resolved by
1553 // this point it never will be
1554 rcx
.tcx().sess
.delay_span_bug(
1556 &format
!("unresolved inference variable in outlives: {:?}", v
));
1562 fn param_ty_must_outlive
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1563 origin
: infer
::SubregionOrigin
<'tcx
>,
1565 param_ty
: ty
::ParamTy
) {
1566 debug
!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1567 region
, param_ty
, origin
);
1569 let verify_bound
= param_bound(rcx
, param_ty
);
1570 let generic
= GenericKind
::Param(param_ty
);
1571 rcx
.fcx
.infcx().verify_generic_bound(origin
, generic
, region
, verify_bound
);
1574 fn projection_must_outlive
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1575 origin
: infer
::SubregionOrigin
<'tcx
>,
1577 projection_ty
: ty
::ProjectionTy
<'tcx
>)
1579 debug
!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1580 region
, projection_ty
, origin
);
1582 // This case is thorny for inference. The fundamental problem is
1583 // that there are many cases where we have choice, and inference
1584 // doesn't like choice (the current region inference in
1585 // particular). :) First off, we have to choose between using the
1586 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1587 // OutlivesProjectionComponent rules, any one of which is
1588 // sufficient. If there are no inference variables involved, it's
1589 // not hard to pick the right rule, but if there are, we're in a
1590 // bit of a catch 22: if we picked which rule we were going to
1591 // use, we could add constraints to the region inference graph
1592 // that make it apply, but if we don't add those constraints, the
1593 // rule might not apply (but another rule might). For now, we err
1594 // on the side of adding too few edges into the graph.
1596 // Compute the bounds we can derive from the environment or trait
1597 // definition. We know that the projection outlives all the
1598 // regions in this list.
1599 let env_bounds
= projection_declared_bounds(rcx
, origin
.span(), projection_ty
);
1601 debug
!("projection_must_outlive: env_bounds={:?}",
1604 // If we know that the projection outlives 'static, then we're
1606 if env_bounds
.contains(&ty
::ReStatic
) {
1607 debug
!("projection_must_outlive: 'static as declared bound");
1611 // If declared bounds list is empty, the only applicable rule is
1612 // OutlivesProjectionComponent. If there are inference variables,
1613 // then, we can break down the outlives into more primitive
1614 // components without adding unnecessary edges.
1616 // If there are *no* inference variables, however, we COULD do
1617 // this, but we choose not to, because the error messages are less
1618 // good. For example, a requirement like `T::Item: 'r` would be
1619 // translated to a requirement that `T: 'r`; when this is reported
1620 // to the user, it will thus say "T: 'r must hold so that T::Item:
1621 // 'r holds". But that makes it sound like the only way to fix
1622 // the problem is to add `T: 'r`, which isn't true. So, if there are no
1623 // inference variables, we use a verify constraint instead of adding
1624 // edges, which winds up enforcing the same condition.
1626 projection_ty
.trait_ref
.substs
.types
.iter().any(|t
| t
.needs_infer()) ||
1627 projection_ty
.trait_ref
.substs
.regions().iter().any(|r
| r
.needs_infer())
1629 if env_bounds
.is_empty() && needs_infer
{
1630 debug
!("projection_must_outlive: no declared bounds");
1632 for &component_ty
in &projection_ty
.trait_ref
.substs
.types
{
1633 type_must_outlive(rcx
, origin
.clone(), component_ty
, region
);
1636 for &r
in projection_ty
.trait_ref
.substs
.regions() {
1637 rcx
.fcx
.mk_subr(origin
.clone(), region
, r
);
1643 // If we find that there is a unique declared bound `'b`, and this bound
1644 // appears in the trait reference, then the best action is to require that `'b:'r`,
1645 // so do that. This is best no matter what rule we use:
1647 // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1648 // the requirement that `'b:'r`
1649 // - OutlivesProjectionComponent: this would require `'b:'r` in addition to other conditions
1650 if !env_bounds
.is_empty() && env_bounds
[1..].iter().all(|b
| *b
== env_bounds
[0]) {
1651 let unique_bound
= env_bounds
[0];
1652 debug
!("projection_must_outlive: unique declared bound = {:?}", unique_bound
);
1653 if projection_ty
.trait_ref
.substs
.regions()
1655 .any(|r
| env_bounds
.contains(r
))
1657 debug
!("projection_must_outlive: unique declared bound appears in trait ref");
1658 rcx
.fcx
.mk_subr(origin
.clone(), region
, unique_bound
);
1663 // Fallback to verifying after the fact that there exists a
1664 // declared bound, or that all the components appearing in the
1665 // projection outlive; in some cases, this may add insufficient
1666 // edges into the inference graph, leading to inference failures
1667 // even though a satisfactory solution exists.
1668 let verify_bound
= projection_bound(rcx
, origin
.span(), env_bounds
, projection_ty
);
1669 let generic
= GenericKind
::Projection(projection_ty
);
1670 rcx
.fcx
.infcx().verify_generic_bound(origin
, generic
.clone(), region
, verify_bound
);
1673 fn type_bound
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>, span
: Span
, ty
: Ty
<'tcx
>) -> VerifyBound
{
1678 ty
::TyProjection(data
) => {
1679 let declared_bounds
= projection_declared_bounds(rcx
, span
, data
);
1680 projection_bound(rcx
, span
, declared_bounds
, data
)
1683 recursive_type_bound(rcx
, span
, ty
)
1688 fn param_bound
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>, param_ty
: ty
::ParamTy
) -> VerifyBound
{
1689 let param_env
= &rcx
.infcx().parameter_environment
;
1691 debug
!("param_bound(param_ty={:?})",
1694 let mut param_bounds
= declared_generic_bounds_from_env(rcx
, GenericKind
::Param(param_ty
));
1696 // Add in the default bound of fn body that applies to all in
1697 // scope type parameters:
1698 param_bounds
.push(param_env
.implicit_region_bound
);
1700 VerifyBound
::AnyRegion(param_bounds
)
1703 fn projection_declared_bounds
<'a
, 'tcx
>(rcx
: &Rcx
<'a
,'tcx
>,
1705 projection_ty
: ty
::ProjectionTy
<'tcx
>)
1708 // First assemble bounds from where clauses and traits.
1710 let mut declared_bounds
=
1711 declared_generic_bounds_from_env(rcx
, GenericKind
::Projection(projection_ty
));
1713 declared_bounds
.extend_from_slice(
1714 &declared_projection_bounds_from_trait(rcx
, span
, projection_ty
));
1719 fn projection_bound
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1721 declared_bounds
: Vec
<ty
::Region
>,
1722 projection_ty
: ty
::ProjectionTy
<'tcx
>)
1724 debug
!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1725 declared_bounds
, projection_ty
);
1727 // see the extensive comment in projection_must_outlive
1729 let ty
= rcx
.tcx().mk_projection(projection_ty
.trait_ref
, projection_ty
.item_name
);
1730 let recursive_bound
= recursive_type_bound(rcx
, span
, ty
);
1732 VerifyBound
::AnyRegion(declared_bounds
).or(recursive_bound
)
1735 fn recursive_type_bound
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1739 let mut bounds
= vec
![];
1741 for subty
in ty
.walk_shallow() {
1742 bounds
.push(type_bound(rcx
, span
, subty
));
1745 let mut regions
= ty
.regions();
1746 regions
.retain(|r
| !r
.is_bound()); // ignore late-bound regions
1747 bounds
.push(VerifyBound
::AllRegions(regions
));
1749 // remove bounds that must hold, since they are not interesting
1750 bounds
.retain(|b
| !b
.must_hold());
1752 if bounds
.len() == 1 {
1753 bounds
.pop().unwrap()
1755 VerifyBound
::AllBounds(bounds
)
1759 fn declared_generic_bounds_from_env
<'a
, 'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1760 generic
: GenericKind
<'tcx
>)
1763 let param_env
= &rcx
.infcx().parameter_environment
;
1765 // To start, collect bounds from user:
1766 let mut param_bounds
= rcx
.tcx().required_region_bounds(generic
.to_ty(rcx
.tcx()),
1767 param_env
.caller_bounds
.clone());
1769 // Next, collect regions we scraped from the well-formedness
1770 // constraints in the fn signature. To do that, we walk the list
1771 // of known relations from the fn ctxt.
1773 // This is crucial because otherwise code like this fails:
1775 // fn foo<'a, A>(x: &'a A) { x.bar() }
1777 // The problem is that the type of `x` is `&'a A`. To be
1778 // well-formed, then, A must be lower-generic by `'a`, but we
1779 // don't know that this holds from first principles.
1780 for &(r
, p
) in &rcx
.region_bound_pairs
{
1781 debug
!("generic={:?} p={:?}",
1785 param_bounds
.push(r
);
1792 fn declared_projection_bounds_from_trait
<'a
,'tcx
>(rcx
: &Rcx
<'a
, 'tcx
>,
1794 projection_ty
: ty
::ProjectionTy
<'tcx
>)
1798 let tcx
= fcx
.tcx();
1799 let infcx
= fcx
.infcx();
1801 debug
!("projection_bounds(projection_ty={:?})",
1804 let ty
= tcx
.mk_projection(projection_ty
.trait_ref
.clone(), projection_ty
.item_name
);
1806 // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1807 // in looking for a trait definition like:
1810 // trait SomeTrait<'a> {
1811 // type SomeType : 'a;
1815 // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1816 let trait_predicates
= tcx
.lookup_predicates(projection_ty
.trait_ref
.def_id
);
1817 let predicates
= trait_predicates
.predicates
.as_slice().to_vec();
1818 traits
::elaborate_predicates(tcx
, predicates
)
1819 .filter_map(|predicate
| {
1820 // we're only interesting in `T : 'a` style predicates:
1821 let outlives
= match predicate
{
1822 ty
::Predicate
::TypeOutlives(data
) => data
,
1823 _
=> { return None; }
1826 debug
!("projection_bounds: outlives={:?} (1)",
1829 // apply the substitutions (and normalize any projected types)
1830 let outlives
= fcx
.instantiate_type_scheme(span
,
1831 projection_ty
.trait_ref
.substs
,
1834 debug
!("projection_bounds: outlives={:?} (2)",
1837 let region_result
= infcx
.commit_if_ok(|_
| {
1839 infcx
.replace_late_bound_regions_with_fresh_var(
1841 infer
::AssocTypeProjection(projection_ty
.item_name
),
1844 debug
!("projection_bounds: outlives={:?} (3)",
1847 // check whether this predicate applies to our current projection
1848 match infer
::mk_eqty(infcx
, false, TypeOrigin
::Misc(span
), ty
, outlives
.0) {
1849 Ok(()) => { Ok(outlives.1) }
1850 Err(_
) => { Err(()) }
1854 debug
!("projection_bounds: region_result={:?}",