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 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::implicator::{self, Implication};
90 use middle::mem_categorization as mc;
91 use middle::mem_categorization::Categorization;
92 use middle::region::CodeExtent;
93 use middle::subst::Substs;
95 use middle::ty::{self, RegionEscape, ReScope, Ty, MethodCall, HasTypeFlags};
96 use middle::infer::{self, GenericKind, InferCtxt, SubregionOrigin, VerifyBound};
98 use middle::ty::adjustment;
99 use middle::ty::wf::ImpliedBound;
104 use syntax::codemap::Span;
105 use rustc_front::visit;
106 use rustc_front::visit::Visitor;
107 use rustc_front::hir;
108 use rustc_front::util as hir_util;
110 use self::SubjectNode::Subject;
112 // a variation on try that just returns unit
113 macro_rules! ignore_err {
114 ($e:expr) => (match $e { Ok(e) => e, Err(_) => return () })
117 ///////////////////////////////////////////////////////////////////////////
118 // PUBLIC ENTRY POINTS
120 pub fn regionck_expr(fcx: &FnCtxt, e: &hir::Expr) {
121 let mut rcx = Rcx::new(fcx, RepeatingScope(e.id), e.id, Subject(e.id));
122 if fcx.err_count_since_creation() == 0 {
123 // regionck assumes typeck succeeded
125 rcx.visit_region_obligations(e.id);
127 rcx.resolve_regions_and_report_errors();
130 /// Region checking during the WF phase for items. `wf_tys` are the
131 /// types from which we should derive implied bounds, if any.
132 pub fn regionck_item<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
133 item_id: ast::NodeId,
135 wf_tys: &[Ty<'tcx>]) {
136 debug!("regionck_item(item.id={:?}, wf_tys={:?}", item_id, wf_tys);
137 let mut rcx = Rcx::new(fcx, RepeatingScope(item_id), item_id, Subject(item_id));
140 .relate_free_regions_from_predicates(tcx, &fcx.infcx().parameter_environment.caller_bounds);
141 rcx.relate_free_regions(wf_tys, item_id, span);
142 rcx.visit_region_obligations(item_id);
143 rcx.resolve_regions_and_report_errors();
146 pub fn regionck_fn(fcx: &FnCtxt,
151 debug!("regionck_fn(id={})", fn_id);
152 let mut rcx = Rcx::new(fcx, RepeatingScope(blk.id), blk.id, Subject(fn_id));
154 if fcx.err_count_since_creation() == 0 {
155 // regionck assumes typeck succeeded
156 rcx.visit_fn_body(fn_id, decl, blk, fn_span);
161 .relate_free_regions_from_predicates(tcx, &fcx.infcx().parameter_environment.caller_bounds);
163 rcx.resolve_regions_and_report_errors();
165 // For the top-level fn, store the free-region-map. We don't store
166 // any map for closures; they just share the same map as the
167 // function that created them.
168 fcx.tcx().store_free_region_map(fn_id, rcx.free_region_map);
171 ///////////////////////////////////////////////////////////////////////////
174 pub struct Rcx<'a, 'tcx: 'a> {
175 pub fcx: &'a FnCtxt<'a, 'tcx>,
177 region_bound_pairs: Vec<(ty::Region, GenericKind<'tcx>)>,
179 free_region_map: FreeRegionMap,
181 // id of innermost fn body id
182 body_id: ast::NodeId,
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,
205 region_bound_pairs: Vec::new(),
206 free_region_map: FreeRegionMap::new(),
210 pub fn tcx(&self) -> &'a ty::ctxt<'tcx> {
214 pub fn infcx(&self) -> &InferCtxt<'a,'tcx> {
218 fn set_body_id(&mut self, body_id: ast::NodeId) -> ast::NodeId {
219 mem::replace(&mut self.body_id, body_id)
222 fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId {
223 mem::replace(&mut self.repeating_scope, scope)
226 /// Try to resolve the type for the given node, returning t_err if an error results. Note that
227 /// we never care about the details of the error, the same error will be detected and reported
228 /// in the writeback phase.
230 /// Note one important point: we do not attempt to resolve *region variables* here. This is
231 /// because regionck is essentially adding constraints to those region variables and so may yet
232 /// influence how they are resolved.
234 /// Consider this silly example:
237 /// fn borrow(x: &int) -> &int {x}
238 /// fn foo(x: @int) -> int { // block: B
239 /// let b = borrow(x); // region: <R0>
244 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
245 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
246 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
247 /// of b will be `&<R0>.int` and then `*b` will require that `<R0>` be bigger than the let and
248 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
249 pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
250 self.fcx.infcx().resolve_type_vars_if_possible(&unresolved_ty)
253 /// Try to resolve the type for the given node.
254 fn resolve_node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
255 let t = self.fcx.node_ty(id);
259 fn resolve_method_type(&self, method_call: MethodCall) -> Option<Ty<'tcx>> {
260 let method_ty = self.fcx.inh.tables.borrow().method_map
261 .get(&method_call).map(|method| method.ty);
262 method_ty.map(|method_ty| self.resolve_type(method_ty))
265 /// Try to resolve the type for the given node.
266 pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> {
267 let ty_unadjusted = self.resolve_node_type(expr.id);
268 if ty_unadjusted.references_error() {
271 ty_unadjusted.adjust(
272 self.fcx.tcx(), expr.span, expr.id,
273 self.fcx.inh.tables.borrow().adjustments.get(&expr.id),
274 |method_call| self.resolve_method_type(method_call))
278 fn visit_fn_body(&mut self,
280 fn_decl: &hir::FnDecl,
284 // When we enter a function, we can derive
285 debug!("visit_fn_body(id={})", id);
288 let fn_sig_map = &self.infcx().tables.borrow().liberated_fn_sigs;
289 match fn_sig_map.get(&id) {
290 Some(f) => f.clone(),
293 &format!("No fn-sig entry for id={}", id));
298 let old_region_bounds_pairs_len = self.region_bound_pairs.len();
300 // Collect the types from which we create inferred bounds.
301 // For the return type, if diverging, substitute `bool` just
302 // because it will have no effect.
304 // FIXME(#25759) return types should not be implied bounds
305 let fn_sig_tys: Vec<_> =
308 .chain(Some(fn_sig.output.unwrap_or(self.tcx().types.bool)))
311 let old_body_id = self.set_body_id(body.id);
312 self.relate_free_regions(&fn_sig_tys[..], body.id, span);
314 self.tcx().region_maps.node_extent(body.id),
315 &fn_decl.inputs[..]);
316 self.visit_block(body);
317 self.visit_region_obligations(body.id);
319 self.region_bound_pairs.truncate(old_region_bounds_pairs_len);
321 self.set_body_id(old_body_id);
324 fn visit_region_obligations(&mut self, node_id: ast::NodeId)
326 debug!("visit_region_obligations: node_id={}", node_id);
328 // region checking can introduce new pending obligations
329 // which, when processed, might generate new region
330 // obligations. So make sure we process those.
331 self.fcx.select_all_obligations_or_error();
333 // Make a copy of the region obligations vec because we'll need
334 // to be able to borrow the fulfillment-cx below when projecting.
335 let region_obligations =
341 .region_obligations(node_id)
344 for r_o in ®ion_obligations {
345 debug!("visit_region_obligations: r_o={:?} cause={:?}",
347 let sup_type = self.resolve_type(r_o.sup_type);
348 let origin = self.code_to_origin(r_o.cause.span, sup_type, &r_o.cause.code);
350 if r_o.sub_region != ty::ReEmpty {
351 type_must_outlive(self, origin, sup_type, r_o.sub_region);
353 self.visit_old_school_wf(node_id, sup_type, origin);
357 // Processing the region obligations should not cause the list to grow further:
358 assert_eq!(region_obligations.len(),
359 self.fcx.inh.infcx.fulfillment_cx.borrow().region_obligations(node_id).len());
362 fn visit_old_school_wf(&mut self,
363 body_id: ast::NodeId,
365 origin: infer::SubregionOrigin<'tcx>) {
366 // As a weird kind of hack, we use a region of empty as a signal
367 // to mean "old-school WF rules". The only reason the old-school
368 // WF rules are not encoded using WF is that this leads to errors,
369 // and we want to phase those in gradually.
371 // FIXME(#27579) remove this weird special case once we phase in new WF rules completely
372 let implications = implicator::implications(self.infcx(),
377 let origin_for_ty = |ty: Option<Ty<'tcx>>| match ty {
378 None => origin.clone(),
379 Some(ty) => infer::ReferenceOutlivesReferent(ty, origin.span()),
381 for implication in implications {
383 Implication::RegionSubRegion(ty, r1, r2) => {
384 self.fcx.mk_subr(origin_for_ty(ty), r1, r2);
386 Implication::RegionSubGeneric(ty, r1, GenericKind::Param(param_ty)) => {
387 param_ty_must_outlive(self, origin_for_ty(ty), r1, param_ty);
389 Implication::RegionSubGeneric(ty, r1, GenericKind::Projection(proj_ty)) => {
390 projection_must_outlive(self, origin_for_ty(ty), r1, proj_ty);
392 Implication::Predicate(def_id, predicate) => {
393 let cause = traits::ObligationCause::new(origin.span(),
395 traits::ItemObligation(def_id));
396 let obligation = traits::Obligation::new(cause, predicate);
397 self.fcx.register_predicate(obligation);
403 fn code_to_origin(&self,
406 code: &traits::ObligationCauseCode<'tcx>)
407 -> SubregionOrigin<'tcx> {
409 traits::ObligationCauseCode::RFC1214(ref code) =>
410 infer::RFC1214Subregion(Rc::new(self.code_to_origin(span, sup_type, code))),
411 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
412 infer::ReferenceOutlivesReferent(ref_type, span),
414 infer::RelateParamBound(span, sup_type),
418 /// This method populates the region map's `free_region_map`. It walks over the transformed
419 /// argument and return types for each function just before we check the body of that function,
420 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
421 /// [usize]`. We do not allow references to outlive the things they point at, so we can assume
422 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
423 /// the caller side, the caller is responsible for checking that the type of every expression
424 /// (including the actual values for the arguments, as well as the return type of the fn call)
427 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
428 fn relate_free_regions(&mut self,
429 fn_sig_tys: &[Ty<'tcx>],
430 body_id: ast::NodeId,
432 debug!("relate_free_regions >>");
434 for &ty in fn_sig_tys {
435 let ty = self.resolve_type(ty);
436 debug!("relate_free_regions(t={:?})", ty);
437 let implied_bounds = ty::wf::implied_bounds(self.fcx.infcx(), body_id, ty, span);
439 // Record any relations between free regions that we observe into the free-region-map.
440 self.free_region_map.relate_free_regions_from_implied_bounds(&implied_bounds);
442 // But also record other relationships, such as `T:'x`,
443 // that don't go into the free-region-map but which we use
445 for implication in implied_bounds {
446 debug!("implication: {:?}", implication);
448 ImpliedBound::RegionSubRegion(ty::ReFree(free_a),
449 ty::ReVar(vid_b)) => {
450 self.fcx.inh.infcx.add_given(free_a, vid_b);
452 ImpliedBound::RegionSubParam(r_a, param_b) => {
453 self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
455 ImpliedBound::RegionSubProjection(r_a, projection_b) => {
456 self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
458 ImpliedBound::RegionSubRegion(..) => {
459 // In principle, we could record (and take
460 // advantage of) every relationship here, but
461 // we are also free not to -- it simply means
462 // strictly less that we can successfully type
463 // check. (It may also be that we should
464 // revise our inference system to be more
465 // general and to make use of *every*
466 // relationship that arises here, but
467 // presently we do not.)
473 debug!("<< relate_free_regions");
476 fn resolve_regions_and_report_errors(&self) {
477 let subject_node_id = match self.subject {
479 SubjectNode::None => {
480 self.tcx().sess.bug("cannot resolve_regions_and_report_errors \
481 without subject node");
485 self.fcx.infcx().resolve_regions_and_report_errors(&self.free_region_map,
490 impl<'a, 'tcx, 'v> Visitor<'v> for Rcx<'a, 'tcx> {
491 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
492 // However, right now we run into an issue whereby some free
493 // regions are not properly related if they appear within the
494 // types of arguments that must be inferred. This could be
495 // addressed by deferring the construction of the region
496 // hierarchy, and in particular the relationships between free
497 // regions, until regionck, as described in #3238.
499 fn visit_fn(&mut self, _fk: visit::FnKind<'v>, fd: &'v hir::FnDecl,
500 b: &'v hir::Block, span: Span, id: ast::NodeId) {
501 self.visit_fn_body(id, fd, b, span)
504 fn visit_item(&mut self, i: &hir::Item) { visit_item(self, i); }
506 fn visit_expr(&mut self, ex: &hir::Expr) { visit_expr(self, ex); }
508 //visit_pat: visit_pat, // (..) see above
510 fn visit_arm(&mut self, a: &hir::Arm) { visit_arm(self, a); }
512 fn visit_local(&mut self, l: &hir::Local) { visit_local(self, l); }
514 fn visit_block(&mut self, b: &hir::Block) { visit_block(self, b); }
517 fn visit_item(_rcx: &mut Rcx, _item: &hir::Item) {
521 fn visit_block(rcx: &mut Rcx, b: &hir::Block) {
522 visit::walk_block(rcx, b);
525 fn visit_arm(rcx: &mut Rcx, arm: &hir::Arm) {
528 constrain_bindings_in_pat(&**p, rcx);
531 visit::walk_arm(rcx, arm);
534 fn visit_local(rcx: &mut Rcx, l: &hir::Local) {
536 constrain_bindings_in_pat(&*l.pat, rcx);
538 visit::walk_local(rcx, l);
541 fn constrain_bindings_in_pat(pat: &hir::Pat, rcx: &mut Rcx) {
542 let tcx = rcx.fcx.tcx();
543 debug!("regionck::visit_pat(pat={:?})", pat);
544 pat_util::pat_bindings(&tcx.def_map, pat, |_, id, span, _| {
545 // If we have a variable that contains region'd data, that
546 // data will be accessible from anywhere that the variable is
547 // accessed. We must be wary of loops like this:
549 // // from src/test/compile-fail/borrowck-lend-flow.rs
550 // let mut v = box 3, w = box 4;
551 // let mut x = &mut w;
554 // borrow(v); //~ ERROR cannot borrow
555 // x = &mut v; // (1)
558 // Typically, we try to determine the region of a borrow from
559 // those points where it is dereferenced. In this case, one
560 // might imagine that the lifetime of `x` need only be the
561 // body of the loop. But of course this is incorrect because
562 // the pointer that is created at point (1) is consumed at
563 // point (2), meaning that it must be live across the loop
564 // iteration. The easiest way to guarantee this is to require
565 // that the lifetime of any regions that appear in a
566 // variable's type enclose at least the variable's scope.
568 let var_scope = tcx.region_maps.var_scope(id);
570 let origin = infer::BindingTypeIsNotValidAtDecl(span);
571 type_of_node_must_outlive(rcx, origin, id, ty::ReScope(var_scope));
573 let typ = rcx.resolve_node_type(id);
574 dropck::check_safety_of_destructor_if_necessary(rcx, typ, span, var_scope);
578 fn visit_expr(rcx: &mut Rcx, expr: &hir::Expr) {
579 debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
580 expr, rcx.repeating_scope);
582 // No matter what, the type of each expression must outlive the
583 // scope of that expression. This also guarantees basic WF.
584 let expr_ty = rcx.resolve_node_type(expr.id);
585 // the region corresponding to this expression
586 let expr_region = ty::ReScope(rcx.tcx().region_maps.node_extent(expr.id));
587 type_must_outlive(rcx, infer::ExprTypeIsNotInScope(expr_ty, expr.span),
588 expr_ty, expr_region);
590 let method_call = MethodCall::expr(expr.id);
591 let opt_method_callee = rcx.fcx.inh.tables.borrow().method_map.get(&method_call).cloned();
592 let has_method_map = opt_method_callee.is_some();
594 // If we are calling a method (either explicitly or via an
595 // overloaded operator), check that all of the types provided as
596 // arguments for its type parameters are well-formed, and all the regions
597 // provided as arguments outlive the call.
598 if let Some(callee) = opt_method_callee {
599 let origin = match expr.node {
600 hir::ExprMethodCall(..) =>
601 infer::ParameterOrigin::MethodCall,
602 hir::ExprUnary(op, _) if op == hir::UnDeref =>
603 infer::ParameterOrigin::OverloadedDeref,
605 infer::ParameterOrigin::OverloadedOperator
608 substs_wf_in_scope(rcx, origin, &callee.substs, expr.span, expr_region);
609 type_must_outlive(rcx, infer::ExprTypeIsNotInScope(callee.ty, expr.span),
610 callee.ty, expr_region);
613 // Check any autoderefs or autorefs that appear.
614 let adjustment = rcx.fcx.inh.tables.borrow().adjustments.get(&expr.id).map(|a| a.clone());
615 if let Some(adjustment) = adjustment {
616 debug!("adjustment={:?}", adjustment);
618 adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
619 autoderefs, ref autoref, ..
621 let expr_ty = rcx.resolve_node_type(expr.id);
622 constrain_autoderefs(rcx, expr, autoderefs, expr_ty);
623 if let Some(ref autoref) = *autoref {
624 link_autoref(rcx, expr, autoderefs, autoref);
626 // Require that the resulting region encompasses
629 // FIXME(#6268) remove to support nested method calls
630 type_of_node_must_outlive(
631 rcx, infer::AutoBorrow(expr.span),
632 expr.id, expr_region);
636 adjustment::AutoObject(_, ref bounds, _, _) => {
637 // Determine if we are casting `expr` to a trait
638 // instance. If so, we have to be sure that the type
639 // of the source obeys the new region bound.
640 let source_ty = rcx.resolve_node_type(expr.id);
641 type_must_outlive(rcx, infer::RelateObjectBound(expr.span),
642 source_ty, bounds.region_bound);
648 // If necessary, constrain destructors in the unadjusted form of this
651 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
652 mc.cat_expr_unadjusted(expr)
656 check_safety_of_rvalue_destructor_if_necessary(rcx,
661 let tcx = rcx.fcx.tcx();
662 tcx.sess.delay_span_bug(expr.span, "cat_expr_unadjusted Errd");
667 // If necessary, constrain destructors in this expression. This will be
668 // the adjusted form if there is an adjustment.
670 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
675 check_safety_of_rvalue_destructor_if_necessary(rcx, head_cmt, expr.span);
678 let tcx = rcx.fcx.tcx();
679 tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
683 debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
684 expr, rcx.repeating_scope);
686 hir::ExprPath(..) => {
687 rcx.fcx.opt_node_ty_substs(expr.id, |item_substs| {
688 let origin = infer::ParameterOrigin::Path;
689 substs_wf_in_scope(rcx, origin, &item_substs.substs, expr.span, expr_region);
693 hir::ExprCall(ref callee, ref args) => {
695 constrain_call(rcx, expr, Some(&**callee),
696 args.iter().map(|e| &**e), false);
698 constrain_callee(rcx, callee.id, expr, &**callee);
699 constrain_call(rcx, expr, None,
700 args.iter().map(|e| &**e), false);
703 visit::walk_expr(rcx, expr);
706 hir::ExprMethodCall(_, _, ref args) => {
707 constrain_call(rcx, expr, Some(&*args[0]),
708 args[1..].iter().map(|e| &**e), false);
710 visit::walk_expr(rcx, expr);
713 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
715 constrain_call(rcx, expr, Some(&**lhs),
716 Some(&**rhs).into_iter(), false);
719 visit::walk_expr(rcx, expr);
722 hir::ExprIndex(ref lhs, ref rhs) if has_method_map => {
723 constrain_call(rcx, expr, Some(&**lhs),
724 Some(&**rhs).into_iter(), true);
726 visit::walk_expr(rcx, expr);
729 hir::ExprBinary(op, ref lhs, ref rhs) if has_method_map => {
730 let implicitly_ref_args = !hir_util::is_by_value_binop(op.node);
732 // As `expr_method_call`, but the call is via an
733 // overloaded op. Note that we (sadly) currently use an
734 // implicit "by ref" sort of passing style here. This
735 // should be converted to an adjustment!
736 constrain_call(rcx, expr, Some(&**lhs),
737 Some(&**rhs).into_iter(), implicitly_ref_args);
739 visit::walk_expr(rcx, expr);
742 hir::ExprBinary(_, ref lhs, ref rhs) => {
743 // If you do `x OP y`, then the types of `x` and `y` must
744 // outlive the operation you are performing.
745 let lhs_ty = rcx.resolve_expr_type_adjusted(&**lhs);
746 let rhs_ty = rcx.resolve_expr_type_adjusted(&**rhs);
747 for &ty in &[lhs_ty, rhs_ty] {
748 type_must_outlive(rcx,
749 infer::Operand(expr.span),
753 visit::walk_expr(rcx, expr);
756 hir::ExprUnary(op, ref lhs) if has_method_map => {
757 let implicitly_ref_args = !hir_util::is_by_value_unop(op);
760 constrain_call(rcx, expr, Some(&**lhs),
761 None::<hir::Expr>.iter(), implicitly_ref_args);
763 visit::walk_expr(rcx, expr);
766 hir::ExprUnary(hir::UnDeref, ref base) => {
767 // For *a, the lifetime of a must enclose the deref
768 let method_call = MethodCall::expr(expr.id);
769 let base_ty = match rcx.fcx.inh.tables.borrow().method_map.get(&method_call) {
771 constrain_call(rcx, expr, Some(&**base),
772 None::<hir::Expr>.iter(), true);
773 let fn_ret = // late-bound regions in overloaded method calls are instantiated
774 rcx.tcx().no_late_bound_regions(&method.ty.fn_ret()).unwrap();
777 None => rcx.resolve_node_type(base.id)
779 if let ty::TyRef(r_ptr, _) = base_ty.sty {
780 mk_subregion_due_to_dereference(
781 rcx, expr.span, expr_region, *r_ptr);
784 visit::walk_expr(rcx, expr);
787 hir::ExprIndex(ref vec_expr, _) => {
788 // For a[b], the lifetime of a must enclose the deref
789 let vec_type = rcx.resolve_expr_type_adjusted(&**vec_expr);
790 constrain_index(rcx, expr, vec_type);
792 visit::walk_expr(rcx, expr);
795 hir::ExprCast(ref source, _) => {
796 // Determine if we are casting `source` to a trait
797 // instance. If so, we have to be sure that the type of
798 // the source obeys the trait's region bound.
799 constrain_cast(rcx, expr, &**source);
800 visit::walk_expr(rcx, expr);
803 hir::ExprAddrOf(m, ref base) => {
804 link_addr_of(rcx, expr, m, &**base);
806 // Require that when you write a `&expr` expression, the
807 // resulting pointer has a lifetime that encompasses the
808 // `&expr` expression itself. Note that we constraining
809 // the type of the node expr.id here *before applying
812 // FIXME(#6268) nested method calls requires that this rule change
813 let ty0 = rcx.resolve_node_type(expr.id);
814 type_must_outlive(rcx, infer::AddrOf(expr.span), ty0, expr_region);
815 visit::walk_expr(rcx, expr);
818 hir::ExprMatch(ref discr, ref arms, _) => {
819 link_match(rcx, &**discr, &arms[..]);
821 visit::walk_expr(rcx, expr);
824 hir::ExprClosure(_, _, ref body) => {
825 check_expr_fn_block(rcx, expr, &**body);
828 hir::ExprLoop(ref body, _) => {
829 let repeating_scope = rcx.set_repeating_scope(body.id);
830 visit::walk_expr(rcx, expr);
831 rcx.set_repeating_scope(repeating_scope);
834 hir::ExprWhile(ref cond, ref body, _) => {
835 let repeating_scope = rcx.set_repeating_scope(cond.id);
836 rcx.visit_expr(&**cond);
838 rcx.set_repeating_scope(body.id);
839 rcx.visit_block(&**body);
841 rcx.set_repeating_scope(repeating_scope);
845 visit::walk_expr(rcx, expr);
850 fn constrain_cast(rcx: &mut Rcx,
851 cast_expr: &hir::Expr,
852 source_expr: &hir::Expr)
854 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
858 let source_ty = rcx.resolve_node_type(source_expr.id);
859 let target_ty = rcx.resolve_node_type(cast_expr.id);
861 walk_cast(rcx, cast_expr, source_ty, target_ty);
863 fn walk_cast<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
864 cast_expr: &hir::Expr,
867 debug!("walk_cast(from_ty={:?}, to_ty={:?})",
870 match (&from_ty.sty, &to_ty.sty) {
871 /*From:*/ (&ty::TyRef(from_r, ref from_mt),
872 /*To: */ &ty::TyRef(to_r, ref to_mt)) => {
873 // Target cannot outlive source, naturally.
874 rcx.fcx.mk_subr(infer::Reborrow(cast_expr.span), *to_r, *from_r);
875 walk_cast(rcx, cast_expr, from_mt.ty, to_mt.ty);
879 /*To: */ &ty::TyTrait(box ty::TraitTy { ref bounds, .. })) => {
880 // When T is existentially quantified as a trait
881 // `Foo+'to`, it must outlive the region bound `'to`.
882 type_must_outlive(rcx, infer::RelateObjectBound(cast_expr.span),
883 from_ty, bounds.region_bound);
886 /*From:*/ (&ty::TyBox(from_referent_ty),
887 /*To: */ &ty::TyBox(to_referent_ty)) => {
888 walk_cast(rcx, cast_expr, from_referent_ty, to_referent_ty);
896 fn check_expr_fn_block(rcx: &mut Rcx,
899 let repeating_scope = rcx.set_repeating_scope(body.id);
900 visit::walk_expr(rcx, expr);
901 rcx.set_repeating_scope(repeating_scope);
904 fn constrain_callee(rcx: &mut Rcx,
905 callee_id: ast::NodeId,
906 _call_expr: &hir::Expr,
907 _callee_expr: &hir::Expr) {
908 let callee_ty = rcx.resolve_node_type(callee_id);
909 match callee_ty.sty {
910 ty::TyBareFn(..) => { }
912 // this should not happen, but it does if the program is
915 // tcx.sess.span_bug(
917 // format!("Calling non-function: {}", callee_ty));
922 fn constrain_call<'a, I: Iterator<Item=&'a hir::Expr>>(rcx: &mut Rcx,
923 call_expr: &hir::Expr,
924 receiver: Option<&hir::Expr>,
926 implicitly_ref_args: bool) {
927 //! Invoked on every call site (i.e., normal calls, method calls,
928 //! and overloaded operators). Constrains the regions which appear
929 //! in the type of the function. Also constrains the regions that
930 //! appear in the arguments appropriately.
932 debug!("constrain_call(call_expr={:?}, \
934 implicitly_ref_args={})",
937 implicitly_ref_args);
939 // `callee_region` is the scope representing the time in which the
942 // FIXME(#6268) to support nested method calls, should be callee_id
943 let callee_scope = rcx.tcx().region_maps.node_extent(call_expr.id);
944 let callee_region = ty::ReScope(callee_scope);
946 debug!("callee_region={:?}", callee_region);
948 for arg_expr in arg_exprs {
949 debug!("Argument: {:?}", arg_expr);
951 // ensure that any regions appearing in the argument type are
952 // valid for at least the lifetime of the function:
953 type_of_node_must_outlive(
954 rcx, infer::CallArg(arg_expr.span),
955 arg_expr.id, callee_region);
957 // unfortunately, there are two means of taking implicit
958 // references, and we need to propagate constraints as a
959 // result. modes are going away and the "DerefArgs" code
960 // should be ported to use adjustments
961 if implicitly_ref_args {
962 link_by_ref(rcx, arg_expr, callee_scope);
966 // as loop above, but for receiver
967 if let Some(r) = receiver {
968 debug!("receiver: {:?}", r);
969 type_of_node_must_outlive(
970 rcx, infer::CallRcvr(r.span),
971 r.id, callee_region);
972 if implicitly_ref_args {
973 link_by_ref(rcx, &*r, callee_scope);
978 /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being
979 /// dereferenced, the lifetime of the pointer includes the deref expr.
980 fn constrain_autoderefs<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
981 deref_expr: &hir::Expr,
983 mut derefd_ty: Ty<'tcx>)
985 debug!("constrain_autoderefs(deref_expr={:?}, derefs={}, derefd_ty={:?})",
990 let s_deref_expr = rcx.tcx().region_maps.node_extent(deref_expr.id);
991 let r_deref_expr = ty::ReScope(s_deref_expr);
993 let method_call = MethodCall::autoderef(deref_expr.id, i as u32);
994 debug!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call, derefs);
996 let method = rcx.fcx.inh.tables.borrow().method_map.get(&method_call).map(|m| m.clone());
998 derefd_ty = match method {
1000 debug!("constrain_autoderefs: #{} is overloaded, method={:?}",
1003 let origin = infer::ParameterOrigin::OverloadedDeref;
1004 substs_wf_in_scope(rcx, origin, method.substs, deref_expr.span, r_deref_expr);
1006 // Treat overloaded autoderefs as if an AutoRef adjustment
1007 // was applied on the base type, as that is always the case.
1008 let fn_sig = method.ty.fn_sig();
1009 let fn_sig = // late-bound regions should have been instantiated
1010 rcx.tcx().no_late_bound_regions(fn_sig).unwrap();
1011 let self_ty = fn_sig.inputs[0];
1012 let (m, r) = match self_ty.sty {
1013 ty::TyRef(r, ref m) => (m.mutbl, r),
1015 rcx.tcx().sess.span_bug(
1017 &format!("bad overloaded deref type {:?}",
1022 debug!("constrain_autoderefs: receiver r={:?} m={:?}",
1026 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1027 let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i));
1028 debug!("constrain_autoderefs: self_cmt={:?}",
1030 link_region(rcx, deref_expr.span, r,
1031 ty::BorrowKind::from_mutbl(m), self_cmt);
1034 // Specialized version of constrain_call.
1035 type_must_outlive(rcx, infer::CallRcvr(deref_expr.span),
1036 self_ty, r_deref_expr);
1037 match fn_sig.output {
1038 ty::FnConverging(return_type) => {
1039 type_must_outlive(rcx, infer::CallReturn(deref_expr.span),
1040 return_type, r_deref_expr);
1043 ty::FnDiverging => unreachable!()
1049 if let ty::TyRef(r_ptr, _) = derefd_ty.sty {
1050 mk_subregion_due_to_dereference(rcx, deref_expr.span,
1051 r_deref_expr, *r_ptr);
1054 match derefd_ty.builtin_deref(true, ty::NoPreference) {
1055 Some(mt) => derefd_ty = mt.ty,
1056 /* if this type can't be dereferenced, then there's already an error
1057 in the session saying so. Just bail out for now */
1063 pub fn mk_subregion_due_to_dereference(rcx: &mut Rcx,
1065 minimum_lifetime: ty::Region,
1066 maximum_lifetime: ty::Region) {
1067 rcx.fcx.mk_subr(infer::DerefPointer(deref_span),
1068 minimum_lifetime, maximum_lifetime)
1071 fn check_safety_of_rvalue_destructor_if_necessary<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
1075 Categorization::Rvalue(region) => {
1077 ty::ReScope(rvalue_scope) => {
1078 let typ = rcx.resolve_type(cmt.ty);
1079 dropck::check_safety_of_destructor_if_necessary(rcx,
1089 &format!("unexpected rvalue region in rvalue \
1090 destructor safety checking: `{:?}`",
1099 /// Invoked on any index expression that occurs. Checks that if this is a slice being indexed, the
1100 /// lifetime of the pointer includes the deref expr.
1101 fn constrain_index<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
1102 index_expr: &hir::Expr,
1103 indexed_ty: Ty<'tcx>)
1105 debug!("constrain_index(index_expr=?, indexed_ty={}",
1106 rcx.fcx.infcx().ty_to_string(indexed_ty));
1108 let r_index_expr = ty::ReScope(rcx.tcx().region_maps.node_extent(index_expr.id));
1109 if let ty::TyRef(r_ptr, mt) = indexed_ty.sty {
1111 ty::TySlice(_) | ty::TyStr => {
1112 rcx.fcx.mk_subr(infer::IndexSlice(index_expr.span),
1113 r_index_expr, *r_ptr);
1120 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1121 /// adjustments) are valid for at least `minimum_lifetime`
1122 fn type_of_node_must_outlive<'a, 'tcx>(
1123 rcx: &mut Rcx<'a, 'tcx>,
1124 origin: infer::SubregionOrigin<'tcx>,
1126 minimum_lifetime: ty::Region)
1128 let tcx = rcx.fcx.tcx();
1130 // Try to resolve the type. If we encounter an error, then typeck
1131 // is going to fail anyway, so just stop here and let typeck
1132 // report errors later on in the writeback phase.
1133 let ty0 = rcx.resolve_node_type(id);
1134 let ty = ty0.adjust(tcx, origin.span(), id,
1135 rcx.fcx.inh.tables.borrow().adjustments.get(&id),
1136 |method_call| rcx.resolve_method_type(method_call));
1137 debug!("constrain_regions_in_type_of_node(\
1138 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
1140 id, minimum_lifetime);
1141 type_must_outlive(rcx, origin, ty, minimum_lifetime);
1144 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1145 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1146 fn link_addr_of(rcx: &mut Rcx, expr: &hir::Expr,
1147 mutability: hir::Mutability, base: &hir::Expr) {
1148 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
1151 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1152 ignore_err!(mc.cat_expr(base))
1155 debug!("link_addr_of: cmt={:?}", cmt);
1157 link_region_from_node_type(rcx, expr.span, expr.id, mutability, cmt);
1160 /// Computes the guarantors for any ref bindings in a `let` and
1161 /// then ensures that the lifetime of the resulting pointer is
1162 /// linked to the lifetime of the initialization expression.
1163 fn link_local(rcx: &Rcx, local: &hir::Local) {
1164 debug!("regionck::for_local()");
1165 let init_expr = match local.init {
1167 Some(ref expr) => &**expr,
1169 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1170 let discr_cmt = ignore_err!(mc.cat_expr(init_expr));
1171 link_pattern(rcx, mc, discr_cmt, &*local.pat);
1174 /// Computes the guarantors for any ref bindings in a match and
1175 /// then ensures that the lifetime of the resulting pointer is
1176 /// linked to the lifetime of its guarantor (if any).
1177 fn link_match(rcx: &Rcx, discr: &hir::Expr, arms: &[hir::Arm]) {
1178 debug!("regionck::for_match()");
1179 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1180 let discr_cmt = ignore_err!(mc.cat_expr(discr));
1181 debug!("discr_cmt={:?}", discr_cmt);
1183 for root_pat in &arm.pats {
1184 link_pattern(rcx, mc, discr_cmt.clone(), &**root_pat);
1189 /// Computes the guarantors for any ref bindings in a match and
1190 /// then ensures that the lifetime of the resulting pointer is
1191 /// linked to the lifetime of its guarantor (if any).
1192 fn link_fn_args(rcx: &Rcx, body_scope: CodeExtent, args: &[hir::Arg]) {
1193 debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1194 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1196 let arg_ty = rcx.fcx.node_ty(arg.id);
1197 let re_scope = ty::ReScope(body_scope);
1198 let arg_cmt = mc.cat_rvalue(arg.id, arg.ty.span, re_scope, arg_ty);
1199 debug!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1203 link_pattern(rcx, mc, arg_cmt, &*arg.pat);
1207 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found in the discriminant, if
1209 fn link_pattern<'t, 'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1210 mc: mc::MemCategorizationContext<'t, 'a, 'tcx>,
1211 discr_cmt: mc::cmt<'tcx>,
1212 root_pat: &hir::Pat) {
1213 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1216 let _ = mc.cat_pattern(discr_cmt, root_pat, |mc, sub_cmt, sub_pat| {
1217 match sub_pat.node {
1219 hir::PatIdent(hir::BindByRef(mutbl), _, _) => {
1220 link_region_from_node_type(
1221 rcx, sub_pat.span, sub_pat.id,
1225 // `[_, ..slice, _]` pattern
1226 hir::PatVec(_, Some(ref slice_pat), _) => {
1227 match mc.cat_slice_pattern(sub_cmt, &**slice_pat) {
1228 Ok((slice_cmt, slice_mutbl, slice_r)) => {
1229 link_region(rcx, sub_pat.span, &slice_r,
1230 ty::BorrowKind::from_mutbl(slice_mutbl),
1241 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1243 fn link_autoref(rcx: &Rcx,
1246 autoref: &adjustment::AutoRef)
1248 debug!("link_autoref(autoref={:?})", autoref);
1249 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1250 let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs));
1251 debug!("expr_cmt={:?}", expr_cmt);
1254 adjustment::AutoPtr(r, m) => {
1255 link_region(rcx, expr.span, r,
1256 ty::BorrowKind::from_mutbl(m), expr_cmt);
1259 adjustment::AutoUnsafe(m) => {
1260 let r = ty::ReScope(rcx.tcx().region_maps.node_extent(expr.id));
1261 link_region(rcx, expr.span, &r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1266 /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and
1267 /// must outlive `callee_scope`.
1268 fn link_by_ref(rcx: &Rcx,
1270 callee_scope: CodeExtent) {
1271 debug!("link_by_ref(expr={:?}, callee_scope={:?})",
1272 expr, callee_scope);
1273 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1274 let expr_cmt = ignore_err!(mc.cat_expr(expr));
1275 let borrow_region = ty::ReScope(callee_scope);
1276 link_region(rcx, expr.span, &borrow_region, ty::ImmBorrow, expr_cmt);
1279 /// Like `link_region()`, except that the region is extracted from the type of `id`, which must be
1280 /// some reference (`&T`, `&str`, etc).
1281 fn link_region_from_node_type<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1284 mutbl: hir::Mutability,
1285 cmt_borrowed: mc::cmt<'tcx>) {
1286 debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1287 id, mutbl, cmt_borrowed);
1289 let rptr_ty = rcx.resolve_node_type(id);
1290 if let ty::TyRef(&r, _) = rptr_ty.sty {
1291 debug!("rptr_ty={}", rptr_ty);
1292 link_region(rcx, span, &r, ty::BorrowKind::from_mutbl(mutbl),
1297 /// Informs the inference engine that `borrow_cmt` is being borrowed with kind `borrow_kind` and
1298 /// lifetime `borrow_region`. In order to ensure borrowck is satisfied, this may create constraints
1299 /// between regions, as explained in `link_reborrowed_region()`.
1300 fn link_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1302 borrow_region: &ty::Region,
1303 borrow_kind: ty::BorrowKind,
1304 borrow_cmt: mc::cmt<'tcx>) {
1305 let mut borrow_cmt = borrow_cmt;
1306 let mut borrow_kind = borrow_kind;
1308 let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1309 type_must_outlive(rcx, origin, borrow_cmt.ty, *borrow_region);
1312 debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1316 match borrow_cmt.cat.clone() {
1317 Categorization::Deref(ref_cmt, _,
1318 mc::Implicit(ref_kind, ref_region)) |
1319 Categorization::Deref(ref_cmt, _,
1320 mc::BorrowedPtr(ref_kind, ref_region)) => {
1321 match link_reborrowed_region(rcx, span,
1322 borrow_region, borrow_kind,
1323 ref_cmt, ref_region, ref_kind,
1335 Categorization::Downcast(cmt_base, _) |
1336 Categorization::Deref(cmt_base, _, mc::Unique) |
1337 Categorization::Interior(cmt_base, _) => {
1338 // Borrowing interior or owned data requires the base
1339 // to be valid and borrowable in the same fashion.
1340 borrow_cmt = cmt_base;
1341 borrow_kind = borrow_kind;
1344 Categorization::Deref(_, _, mc::UnsafePtr(..)) |
1345 Categorization::StaticItem |
1346 Categorization::Upvar(..) |
1347 Categorization::Local(..) |
1348 Categorization::Rvalue(..) => {
1349 // These are all "base cases" with independent lifetimes
1350 // that are not subject to inference
1357 /// This is the most complicated case: the path being borrowed is
1358 /// itself the referent of a borrowed pointer. Let me give an
1359 /// example fragment of code to make clear(er) the situation:
1361 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1363 /// &'z *r // the reborrow has lifetime 'z
1365 /// Now, in this case, our primary job is to add the inference
1366 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1367 /// parameters in (roughly) terms of the example:
1369 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1370 /// borrow_region ^~ ref_region ^~
1371 /// borrow_kind ^~ ref_kind ^~
1374 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1376 /// Unfortunately, there are some complications beyond the simple
1377 /// scenario I just painted:
1379 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1380 /// case, we have two jobs. First, we are inferring whether this reference
1381 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1382 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1383 /// then `r` must be an `&mut` reference). Second, whenever we link
1384 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1385 /// case we adjust the cause to indicate that the reference being
1386 /// "reborrowed" is itself an upvar. This provides a nicer error message
1387 /// should something go wrong.
1389 /// 2. There may in fact be more levels of reborrowing. In the
1390 /// example, I said the borrow was like `&'z *r`, but it might
1391 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1392 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1393 /// and `'z <= 'b`. This is explained more below.
1395 /// The return value of this function indicates whether we need to
1396 /// recurse and process `ref_cmt` (see case 2 above).
1397 fn link_reborrowed_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1399 borrow_region: &ty::Region,
1400 borrow_kind: ty::BorrowKind,
1401 ref_cmt: mc::cmt<'tcx>,
1402 ref_region: ty::Region,
1403 mut ref_kind: ty::BorrowKind,
1405 -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1407 // Possible upvar ID we may need later to create an entry in the
1410 // Detect by-ref upvar `x`:
1411 let cause = match note {
1412 mc::NoteUpvarRef(ref upvar_id) => {
1413 let upvar_capture_map = &rcx.fcx.inh.tables.borrow_mut().upvar_capture_map;
1414 match upvar_capture_map.get(upvar_id) {
1415 Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1416 // The mutability of the upvar may have been modified
1417 // by the above adjustment, so update our local variable.
1418 ref_kind = upvar_borrow.kind;
1420 infer::ReborrowUpvar(span, *upvar_id)
1423 rcx.tcx().sess.span_bug(
1425 &format!("Illegal upvar id: {:?}",
1430 mc::NoteClosureEnv(ref upvar_id) => {
1431 // We don't have any mutability changes to propagate, but
1432 // we do want to note that an upvar reborrow caused this
1434 infer::ReborrowUpvar(span, *upvar_id)
1437 infer::Reborrow(span)
1441 debug!("link_reborrowed_region: {:?} <= {:?}",
1444 rcx.fcx.mk_subr(cause, *borrow_region, ref_region);
1446 // If we end up needing to recurse and establish a region link
1447 // with `ref_cmt`, calculate what borrow kind we will end up
1448 // needing. This will be used below.
1450 // One interesting twist is that we can weaken the borrow kind
1451 // when we recurse: to reborrow an `&mut` referent as mutable,
1452 // borrowck requires a unique path to the `&mut` reference but not
1453 // necessarily a *mutable* path.
1454 let new_borrow_kind = match borrow_kind {
1457 ty::MutBorrow | ty::UniqueImmBorrow =>
1461 // Decide whether we need to recurse and link any regions within
1462 // the `ref_cmt`. This is concerned for the case where the value
1463 // being reborrowed is in fact a borrowed pointer found within
1464 // another borrowed pointer. For example:
1466 // let p: &'b &'a mut T = ...;
1470 // What makes this case particularly tricky is that, if the data
1471 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1472 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1473 // (otherwise the user might mutate through the `&mut T` reference
1474 // after `'b` expires and invalidate the borrow we are looking at
1477 // So let's re-examine our parameters in light of this more
1478 // complicated (possible) scenario:
1480 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1481 // borrow_region ^~ ref_region ^~
1482 // borrow_kind ^~ ref_kind ^~
1485 // (Note that since we have not examined `ref_cmt.cat`, we don't
1486 // know whether this scenario has occurred; but I wanted to show
1487 // how all the types get adjusted.)
1490 // The reference being reborrowed is a sharable ref of
1491 // type `&'a T`. In this case, it doesn't matter where we
1492 // *found* the `&T` pointer, the memory it references will
1493 // be valid and immutable for `'a`. So we can stop here.
1495 // (Note that the `borrow_kind` must also be ImmBorrow or
1496 // else the user is borrowed imm memory as mut memory,
1497 // which means they'll get an error downstream in borrowck
1502 ty::MutBorrow | ty::UniqueImmBorrow => {
1503 // The reference being reborrowed is either an `&mut T` or
1504 // `&uniq T`. This is the case where recursion is needed.
1505 return Some((ref_cmt, new_borrow_kind));
1510 /// Checks that the values provided for type/region arguments in a given
1511 /// expression are well-formed and in-scope.
1512 pub fn substs_wf_in_scope<'a,'tcx>(rcx: &mut Rcx<'a,'tcx>,
1513 origin: infer::ParameterOrigin,
1514 substs: &Substs<'tcx>,
1516 expr_region: ty::Region) {
1517 debug!("substs_wf_in_scope(substs={:?}, \
1521 substs, expr_region, origin, expr_span);
1523 let origin = infer::ParameterInScope(origin, expr_span);
1525 for ®ion in substs.regions() {
1526 rcx.fcx.mk_subr(origin.clone(), expr_region, region);
1529 for &ty in &substs.types {
1530 let ty = rcx.resolve_type(ty);
1531 type_must_outlive(rcx, origin.clone(), ty, expr_region);
1535 /// Ensures that type is well-formed in `region`, which implies (among
1536 /// other things) that all borrowed data reachable via `ty` outlives
1538 pub fn type_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1539 origin: infer::SubregionOrigin<'tcx>,
1543 let ty = rcx.resolve_type(ty);
1545 debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})",
1550 assert!(!ty.has_escaping_regions());
1552 let components = ty::outlives::components(rcx.infcx(), ty);
1553 components_must_outlive(rcx, origin, components, region);
1556 fn components_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1557 origin: infer::SubregionOrigin<'tcx>,
1558 components: Vec<ty::outlives::Component<'tcx>>,
1561 for component in components {
1562 let origin = origin.clone();
1564 ty::outlives::Component::Region(region1) => {
1565 rcx.fcx.mk_subr(origin, region, region1);
1567 ty::outlives::Component::Param(param_ty) => {
1568 param_ty_must_outlive(rcx, origin, region, param_ty);
1570 ty::outlives::Component::Projection(projection_ty) => {
1571 projection_must_outlive(rcx, origin, region, projection_ty);
1573 ty::outlives::Component::EscapingProjection(subcomponents) => {
1574 components_must_outlive(rcx, origin, subcomponents, region);
1576 ty::outlives::Component::UnresolvedInferenceVariable(v) => {
1577 // ignore this, we presume it will yield an error
1578 // later, since if a type variable is not resolved by
1579 // this point it never will be
1580 rcx.tcx().sess.delay_span_bug(
1582 &format!("unresolved inference variable in outlives: {:?}", v));
1584 ty::outlives::Component::RFC1214(subcomponents) => {
1585 let suborigin = infer::RFC1214Subregion(Rc::new(origin));
1586 components_must_outlive(rcx, suborigin, subcomponents, region);
1592 fn param_ty_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1593 origin: infer::SubregionOrigin<'tcx>,
1595 param_ty: ty::ParamTy) {
1596 debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1597 region, param_ty, origin);
1599 let verify_bound = param_bound(rcx, param_ty);
1600 let generic = GenericKind::Param(param_ty);
1601 rcx.fcx.infcx().verify_generic_bound(origin, generic, region, verify_bound);
1604 fn projection_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1605 origin: infer::SubregionOrigin<'tcx>,
1607 projection_ty: ty::ProjectionTy<'tcx>)
1609 debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1610 region, projection_ty, origin);
1612 // This case is thorny for inference. The fundamental problem is
1613 // that there are many cases where we have choice, and inference
1614 // doesn't like choice (the current region inference in
1615 // particular). :) First off, we have to choose between using the
1616 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1617 // OutlivesProjectionComponent rules, any one of which is
1618 // sufficient. If there are no inference variables involved, it's
1619 // not hard to pick the right rule, but if there are, we're in a
1620 // bit of a catch 22: if we picked which rule we were going to
1621 // use, we could add constraints to the region inference graph
1622 // that make it apply, but if we don't add those constraints, the
1623 // rule might not apply (but another rule might). For now, we err
1624 // on the side of adding too few edges into the graph.
1626 // Compute the bounds we can derive from the environment or trait
1627 // definition. We know that the projection outlives all the
1628 // regions in this list.
1629 let env_bounds = projection_declared_bounds(rcx, origin.span(), projection_ty);
1631 debug!("projection_must_outlive: env_bounds={:?}",
1634 // If we know that the projection outlives 'static, then we're
1636 if env_bounds.contains(&ty::ReStatic) {
1637 debug!("projection_must_outlive: 'static as declared bound");
1641 // If declared bounds list is empty, the only applicable rule is
1642 // OutlivesProjectionComponent. If there are inference variables,
1643 // then, we can break down the outlives into more primitive
1644 // components without adding unnecessary edges.
1646 // If there are *no* inference variables, however, we COULD do
1647 // this, but we choose not to, because the error messages are less
1648 // good. For example, a requirement like `T::Item: 'r` would be
1649 // translated to a requirement that `T: 'r`; when this is reported
1650 // to the user, it will thus say "T: 'r must hold so that T::Item:
1651 // 'r holds". But that makes it sound like the only way to fix
1652 // the problem is to add `T: 'r`, which isn't true. So, if there are no
1653 // inference variables, we use a verify constraint instead of adding
1654 // edges, which winds up enforcing the same condition.
1656 projection_ty.trait_ref.substs.types.iter().any(|t| t.needs_infer()) ||
1657 projection_ty.trait_ref.substs.regions().iter().any(|r| r.needs_infer())
1659 if env_bounds.is_empty() && needs_infer {
1660 debug!("projection_must_outlive: no declared bounds");
1662 for &component_ty in &projection_ty.trait_ref.substs.types {
1663 type_must_outlive(rcx, origin.clone(), component_ty, region);
1666 for &r in projection_ty.trait_ref.substs.regions() {
1667 rcx.fcx.mk_subr(origin.clone(), region, r);
1673 // If we find that there is a unique declared bound `'b`, and this bound
1674 // appears in the trait reference, then the best action is to require that `'b:'r`,
1675 // so do that. This is best no matter what rule we use:
1677 // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1678 // the requirement that `'b:'r`
1679 // - OutlivesProjectionComponent: this would require `'b:'r` in addition to other conditions
1680 if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) {
1681 let unique_bound = env_bounds[0];
1682 debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound);
1683 if projection_ty.trait_ref.substs.regions()
1685 .any(|r| env_bounds.contains(r))
1687 debug!("projection_must_outlive: unique declared bound appears in trait ref");
1688 rcx.fcx.mk_subr(origin.clone(), region, unique_bound);
1693 // Fallback to verifying after the fact that there exists a
1694 // declared bound, or that all the components appearing in the
1695 // projection outlive; in some cases, this may add insufficient
1696 // edges into the inference graph, leading to inference failures
1697 // even though a satisfactory solution exists.
1698 let verify_bound = projection_bound(rcx, origin.span(), env_bounds, projection_ty);
1699 let generic = GenericKind::Projection(projection_ty);
1700 rcx.fcx.infcx().verify_generic_bound(origin, generic.clone(), region, verify_bound);
1703 fn type_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, span: Span, ty: Ty<'tcx>) -> VerifyBound {
1708 ty::TyProjection(data) => {
1709 let declared_bounds = projection_declared_bounds(rcx, span, data);
1710 projection_bound(rcx, span, declared_bounds, data)
1713 recursive_type_bound(rcx, span, ty)
1718 fn param_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, param_ty: ty::ParamTy) -> VerifyBound {
1719 let param_env = &rcx.infcx().parameter_environment;
1721 debug!("param_bound(param_ty={:?})",
1724 let mut param_bounds = declared_generic_bounds_from_env(rcx, GenericKind::Param(param_ty));
1726 // Add in the default bound of fn body that applies to all in
1727 // scope type parameters:
1728 param_bounds.push(param_env.implicit_region_bound);
1730 VerifyBound::AnyRegion(param_bounds)
1733 fn projection_declared_bounds<'a, 'tcx>(rcx: &Rcx<'a,'tcx>,
1735 projection_ty: ty::ProjectionTy<'tcx>)
1738 // First assemble bounds from where clauses and traits.
1740 let mut declared_bounds =
1741 declared_generic_bounds_from_env(rcx, GenericKind::Projection(projection_ty));
1743 declared_bounds.push_all(
1744 &declared_projection_bounds_from_trait(rcx, span, projection_ty));
1749 fn projection_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1751 declared_bounds: Vec<ty::Region>,
1752 projection_ty: ty::ProjectionTy<'tcx>)
1754 debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1755 declared_bounds, projection_ty);
1757 // see the extensive comment in projection_must_outlive
1759 let ty = rcx.tcx().mk_projection(projection_ty.trait_ref, projection_ty.item_name);
1760 let recursive_bound = recursive_type_bound(rcx, span, ty);
1762 VerifyBound::AnyRegion(declared_bounds).or(recursive_bound)
1765 fn recursive_type_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1769 let mut bounds = vec![];
1771 for subty in ty.walk_shallow() {
1772 bounds.push(type_bound(rcx, span, subty));
1775 let mut regions = ty.regions();
1776 regions.retain(|r| !r.is_bound()); // ignore late-bound regions
1777 bounds.push(VerifyBound::AllRegions(regions));
1779 // remove bounds that must hold, since they are not interesting
1780 bounds.retain(|b| !b.must_hold());
1782 if bounds.len() == 1 {
1783 bounds.pop().unwrap()
1785 VerifyBound::AllBounds(bounds)
1789 fn declared_generic_bounds_from_env<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1790 generic: GenericKind<'tcx>)
1793 let param_env = &rcx.infcx().parameter_environment;
1795 // To start, collect bounds from user:
1796 let mut param_bounds = rcx.tcx().required_region_bounds(generic.to_ty(rcx.tcx()),
1797 param_env.caller_bounds.clone());
1799 // Next, collect regions we scraped from the well-formedness
1800 // constraints in the fn signature. To do that, we walk the list
1801 // of known relations from the fn ctxt.
1803 // This is crucial because otherwise code like this fails:
1805 // fn foo<'a, A>(x: &'a A) { x.bar() }
1807 // The problem is that the type of `x` is `&'a A`. To be
1808 // well-formed, then, A must be lower-generic by `'a`, but we
1809 // don't know that this holds from first principles.
1810 for &(r, p) in &rcx.region_bound_pairs {
1811 debug!("generic={:?} p={:?}",
1815 param_bounds.push(r);
1822 fn declared_projection_bounds_from_trait<'a,'tcx>(rcx: &Rcx<'a, 'tcx>,
1824 projection_ty: ty::ProjectionTy<'tcx>)
1828 let tcx = fcx.tcx();
1829 let infcx = fcx.infcx();
1831 debug!("projection_bounds(projection_ty={:?})",
1834 let ty = tcx.mk_projection(projection_ty.trait_ref.clone(), projection_ty.item_name);
1836 // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1837 // in looking for a trait definition like:
1840 // trait SomeTrait<'a> {
1841 // type SomeType : 'a;
1845 // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1846 let trait_predicates = tcx.lookup_predicates(projection_ty.trait_ref.def_id);
1847 let predicates = trait_predicates.predicates.as_slice().to_vec();
1848 traits::elaborate_predicates(tcx, predicates)
1849 .filter_map(|predicate| {
1850 // we're only interesting in `T : 'a` style predicates:
1851 let outlives = match predicate {
1852 ty::Predicate::TypeOutlives(data) => data,
1853 _ => { return None; }
1856 debug!("projection_bounds: outlives={:?} (1)",
1859 // apply the substitutions (and normalize any projected types)
1860 let outlives = fcx.instantiate_type_scheme(span,
1861 projection_ty.trait_ref.substs,
1864 debug!("projection_bounds: outlives={:?} (2)",
1867 let region_result = infcx.commit_if_ok(|_| {
1869 infcx.replace_late_bound_regions_with_fresh_var(
1871 infer::AssocTypeProjection(projection_ty.item_name),
1874 debug!("projection_bounds: outlives={:?} (3)",
1877 // check whether this predicate applies to our current projection
1878 match infer::mk_eqty(infcx, false, infer::Misc(span), ty, outlives.0) {
1879 Ok(()) => { Ok(outlives.1) }
1880 Err(_) => { Err(()) }
1884 debug!("projection_bounds: region_result={:?}",