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 it the region of the borrowed pointer that was
81 //! traversed. This is essentially the same as the ownership
82 //! relation, except that a borrowed pointer never owns its
88 use middle::free_region::FreeRegionMap;
89 use middle::implicator::{self, Implication};
90 use middle::mem_categorization as mc;
91 use middle::region::CodeExtent;
92 use middle::subst::Substs;
94 use middle::ty::{self, RegionEscape, ReScope, Ty, MethodCall, HasTypeFlags};
95 use middle::infer::{self, GenericKind, InferCtxt, SubregionOrigin, VerifyBound};
97 use middle::ty::adjustment;
98 use middle::ty::wf::ImpliedBound;
103 use syntax::codemap::Span;
104 use rustc_front::visit;
105 use rustc_front::visit::Visitor;
106 use rustc_front::hir;
107 use rustc_front::util as hir_util;
109 use self::SubjectNode::Subject;
111 // a variation on try that just returns unit
112 macro_rules! ignore_err {
113 ($e:expr) => (match $e { Ok(e) => e, Err(_) => return () })
116 ///////////////////////////////////////////////////////////////////////////
117 // PUBLIC ENTRY POINTS
119 pub fn regionck_expr(fcx: &FnCtxt, e: &hir::Expr) {
120 let mut rcx = Rcx::new(fcx, RepeatingScope(e.id), e.id, Subject(e.id));
121 if fcx.err_count_since_creation() == 0 {
122 // regionck assumes typeck succeeded
124 rcx.visit_region_obligations(e.id);
126 rcx.resolve_regions_and_report_errors();
129 /// Region checking during the WF phase for items. `wf_tys` are the
130 /// types from which we should derive implied bounds, if any.
131 pub fn regionck_item<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
132 item_id: ast::NodeId,
134 wf_tys: &[Ty<'tcx>]) {
135 debug!("regionck_item(item.id={:?}, wf_tys={:?}", item_id, wf_tys);
136 let mut rcx = Rcx::new(fcx, RepeatingScope(item_id), item_id, Subject(item_id));
139 .relate_free_regions_from_predicates(tcx, &fcx.infcx().parameter_environment.caller_bounds);
140 rcx.relate_free_regions(wf_tys, item_id, span);
141 rcx.visit_region_obligations(item_id);
142 rcx.resolve_regions_and_report_errors();
145 pub fn regionck_fn(fcx: &FnCtxt,
150 debug!("regionck_fn(id={})", fn_id);
151 let mut rcx = Rcx::new(fcx, RepeatingScope(blk.id), blk.id, Subject(fn_id));
153 if fcx.err_count_since_creation() == 0 {
154 // regionck assumes typeck succeeded
155 rcx.visit_fn_body(fn_id, decl, blk, fn_span);
160 .relate_free_regions_from_predicates(tcx, &fcx.infcx().parameter_environment.caller_bounds);
162 rcx.resolve_regions_and_report_errors();
164 // For the top-level fn, store the free-region-map. We don't store
165 // any map for closures; they just share the same map as the
166 // function that created them.
167 fcx.tcx().store_free_region_map(fn_id, rcx.free_region_map);
170 ///////////////////////////////////////////////////////////////////////////
173 pub struct Rcx<'a, 'tcx: 'a> {
174 pub fcx: &'a FnCtxt<'a, 'tcx>,
176 region_bound_pairs: Vec<(ty::Region, GenericKind<'tcx>)>,
178 free_region_map: FreeRegionMap,
180 // id of innermost fn body id
181 body_id: ast::NodeId,
183 // id of innermost fn or loop
184 repeating_scope: ast::NodeId,
186 // id of AST node being analyzed (the subject of the analysis).
187 subject: SubjectNode,
191 pub struct RepeatingScope(ast::NodeId);
192 pub enum SubjectNode { Subject(ast::NodeId), None }
194 impl<'a, 'tcx> Rcx<'a, 'tcx> {
195 pub fn new(fcx: &'a FnCtxt<'a, 'tcx>,
196 initial_repeating_scope: RepeatingScope,
197 initial_body_id: ast::NodeId,
198 subject: SubjectNode) -> Rcx<'a, 'tcx> {
199 let RepeatingScope(initial_repeating_scope) = initial_repeating_scope;
201 repeating_scope: initial_repeating_scope,
202 body_id: initial_body_id,
204 region_bound_pairs: Vec::new(),
205 free_region_map: FreeRegionMap::new(),
209 pub fn tcx(&self) -> &'a ty::ctxt<'tcx> {
213 pub fn infcx(&self) -> &InferCtxt<'a,'tcx> {
217 fn set_body_id(&mut self, body_id: ast::NodeId) -> ast::NodeId {
218 mem::replace(&mut self.body_id, body_id)
221 fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId {
222 mem::replace(&mut self.repeating_scope, scope)
225 /// Try to resolve the type for the given node, returning t_err if an error results. Note that
226 /// we never care about the details of the error, the same error will be detected and reported
227 /// in the writeback phase.
229 /// Note one important point: we do not attempt to resolve *region variables* here. This is
230 /// because regionck is essentially adding constraints to those region variables and so may yet
231 /// influence how they are resolved.
233 /// Consider this silly example:
236 /// fn borrow(x: &int) -> &int {x}
237 /// fn foo(x: @int) -> int { // block: B
238 /// let b = borrow(x); // region: <R0>
243 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
244 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
245 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
246 /// of b will be `&<R0>.int` and then `*b` will require that `<R0>` be bigger than the let and
247 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
248 pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
249 self.fcx.infcx().resolve_type_vars_if_possible(&unresolved_ty)
252 /// Try to resolve the type for the given node.
253 fn resolve_node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
254 let t = self.fcx.node_ty(id);
258 fn resolve_method_type(&self, method_call: MethodCall) -> Option<Ty<'tcx>> {
259 let method_ty = self.fcx.inh.tables.borrow().method_map
260 .get(&method_call).map(|method| method.ty);
261 method_ty.map(|method_ty| self.resolve_type(method_ty))
264 /// Try to resolve the type for the given node.
265 pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> {
266 let ty_unadjusted = self.resolve_node_type(expr.id);
267 if ty_unadjusted.references_error() {
270 ty_unadjusted.adjust(
271 self.fcx.tcx(), expr.span, expr.id,
272 self.fcx.inh.tables.borrow().adjustments.get(&expr.id),
273 |method_call| self.resolve_method_type(method_call))
277 fn visit_fn_body(&mut self,
279 fn_decl: &hir::FnDecl,
283 // When we enter a function, we can derive
284 debug!("visit_fn_body(id={})", id);
286 let fn_sig_map = self.fcx.inh.fn_sig_map.borrow();
287 let fn_sig = match fn_sig_map.get(&id) {
291 &format!("No fn-sig entry for id={}", id));
295 let old_region_bounds_pairs_len = self.region_bound_pairs.len();
297 let old_body_id = self.set_body_id(body.id);
298 self.relate_free_regions(&fn_sig[..], body.id, span);
300 self.tcx().region_maps.node_extent(body.id),
301 &fn_decl.inputs[..]);
302 self.visit_block(body);
303 self.visit_region_obligations(body.id);
305 self.region_bound_pairs.truncate(old_region_bounds_pairs_len);
307 self.set_body_id(old_body_id);
310 fn visit_region_obligations(&mut self, node_id: ast::NodeId)
312 debug!("visit_region_obligations: node_id={}", node_id);
314 // region checking can introduce new pending obligations
315 // which, when processed, might generate new region
316 // obligations. So make sure we process those.
317 self.fcx.select_all_obligations_or_error();
319 // Make a copy of the region obligations vec because we'll need
320 // to be able to borrow the fulfillment-cx below when projecting.
321 let region_obligations =
327 .region_obligations(node_id)
330 for r_o in ®ion_obligations {
331 debug!("visit_region_obligations: r_o={:?} cause={:?}",
333 let sup_type = self.resolve_type(r_o.sup_type);
334 let origin = self.code_to_origin(r_o.cause.span, sup_type, &r_o.cause.code);
336 if r_o.sub_region != ty::ReEmpty {
337 type_must_outlive(self, origin, sup_type, r_o.sub_region);
339 self.visit_old_school_wf(node_id, sup_type, origin);
343 // Processing the region obligations should not cause the list to grow further:
344 assert_eq!(region_obligations.len(),
345 self.fcx.inh.infcx.fulfillment_cx.borrow().region_obligations(node_id).len());
348 fn visit_old_school_wf(&mut self,
349 body_id: ast::NodeId,
351 origin: infer::SubregionOrigin<'tcx>) {
352 // As a weird kind of hack, we use a region of empty as a signal
353 // to mean "old-school WF rules". The only reason the old-school
354 // WF rules are not encoded using WF is that this leads to errors,
355 // and we want to phase those in gradually.
357 // FIXME(#27579) remove this weird special case once we phase in new WF rules completely
358 let implications = implicator::implications(self.infcx(),
363 let origin_for_ty = |ty: Option<Ty<'tcx>>| match ty {
364 None => origin.clone(),
365 Some(ty) => infer::ReferenceOutlivesReferent(ty, origin.span()),
367 for implication in implications {
369 Implication::RegionSubRegion(ty, r1, r2) => {
370 self.fcx.mk_subr(origin_for_ty(ty), r1, r2);
372 Implication::RegionSubGeneric(ty, r1, GenericKind::Param(param_ty)) => {
373 param_ty_must_outlive(self, origin_for_ty(ty), r1, param_ty);
375 Implication::RegionSubGeneric(ty, r1, GenericKind::Projection(proj_ty)) => {
376 projection_must_outlive(self, origin_for_ty(ty), r1, proj_ty);
378 Implication::Predicate(def_id, predicate) => {
379 let cause = traits::ObligationCause::new(origin.span(),
381 traits::ItemObligation(def_id));
382 let obligation = traits::Obligation::new(cause, predicate);
383 self.fcx.register_predicate(obligation);
389 fn code_to_origin(&self,
392 code: &traits::ObligationCauseCode<'tcx>)
393 -> SubregionOrigin<'tcx> {
395 traits::ObligationCauseCode::RFC1214(ref code) =>
396 infer::RFC1214Subregion(Rc::new(self.code_to_origin(span, sup_type, code))),
397 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
398 infer::ReferenceOutlivesReferent(ref_type, span),
400 infer::RelateParamBound(span, sup_type),
404 /// This method populates the region map's `free_region_map`. It walks over the transformed
405 /// argument and return types for each function just before we check the body of that function,
406 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
407 /// [usize]`. We do not allow references to outlive the things they point at, so we can assume
408 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
409 /// the caller side, the caller is responsible for checking that the type of every expression
410 /// (including the actual values for the arguments, as well as the return type of the fn call)
413 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
414 fn relate_free_regions(&mut self,
415 fn_sig_tys: &[Ty<'tcx>],
416 body_id: ast::NodeId,
418 debug!("relate_free_regions >>");
420 for &ty in fn_sig_tys {
421 let ty = self.resolve_type(ty);
422 debug!("relate_free_regions(t={:?})", ty);
423 let implied_bounds = ty::wf::implied_bounds(self.fcx.infcx(), body_id, ty, span);
425 // Record any relations between free regions that we observe into the free-region-map.
426 self.free_region_map.relate_free_regions_from_implied_bounds(&implied_bounds);
428 // But also record other relationships, such as `T:'x`,
429 // that don't go into the free-region-map but which we use
431 for implication in implied_bounds {
432 debug!("implication: {:?}", implication);
434 ImpliedBound::RegionSubRegion(ty::ReFree(free_a),
435 ty::ReVar(vid_b)) => {
436 self.fcx.inh.infcx.add_given(free_a, vid_b);
438 ImpliedBound::RegionSubParam(r_a, param_b) => {
439 self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
441 ImpliedBound::RegionSubProjection(r_a, projection_b) => {
442 self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
444 ImpliedBound::RegionSubRegion(..) => {
445 // In principle, we could record (and take
446 // advantage of) every relationship here, but
447 // we are also free not to -- it simply means
448 // strictly less that we can successfully type
449 // check. (It may also be that we should
450 // revise our inference system to be more
451 // general and to make use of *every*
452 // relationship that arises here, but
453 // presently we do not.)
459 debug!("<< relate_free_regions");
462 fn resolve_regions_and_report_errors(&self) {
463 let subject_node_id = match self.subject {
465 SubjectNode::None => {
466 self.tcx().sess.bug("cannot resolve_regions_and_report_errors \
467 without subject node");
471 self.fcx.infcx().resolve_regions_and_report_errors(&self.free_region_map,
476 impl<'a, 'tcx, 'v> Visitor<'v> for Rcx<'a, 'tcx> {
477 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
478 // However, right now we run into an issue whereby some free
479 // regions are not properly related if they appear within the
480 // types of arguments that must be inferred. This could be
481 // addressed by deferring the construction of the region
482 // hierarchy, and in particular the relationships between free
483 // regions, until regionck, as described in #3238.
485 fn visit_fn(&mut self, _fk: visit::FnKind<'v>, fd: &'v hir::FnDecl,
486 b: &'v hir::Block, span: Span, id: ast::NodeId) {
487 self.visit_fn_body(id, fd, b, span)
490 fn visit_item(&mut self, i: &hir::Item) { visit_item(self, i); }
492 fn visit_expr(&mut self, ex: &hir::Expr) { visit_expr(self, ex); }
494 //visit_pat: visit_pat, // (..) see above
496 fn visit_arm(&mut self, a: &hir::Arm) { visit_arm(self, a); }
498 fn visit_local(&mut self, l: &hir::Local) { visit_local(self, l); }
500 fn visit_block(&mut self, b: &hir::Block) { visit_block(self, b); }
503 fn visit_item(_rcx: &mut Rcx, _item: &hir::Item) {
507 fn visit_block(rcx: &mut Rcx, b: &hir::Block) {
508 visit::walk_block(rcx, b);
511 fn visit_arm(rcx: &mut Rcx, arm: &hir::Arm) {
514 constrain_bindings_in_pat(&**p, rcx);
517 visit::walk_arm(rcx, arm);
520 fn visit_local(rcx: &mut Rcx, l: &hir::Local) {
522 constrain_bindings_in_pat(&*l.pat, rcx);
524 visit::walk_local(rcx, l);
527 fn constrain_bindings_in_pat(pat: &hir::Pat, rcx: &mut Rcx) {
528 let tcx = rcx.fcx.tcx();
529 debug!("regionck::visit_pat(pat={:?})", pat);
530 pat_util::pat_bindings(&tcx.def_map, pat, |_, id, span, _| {
531 // If we have a variable that contains region'd data, that
532 // data will be accessible from anywhere that the variable is
533 // accessed. We must be wary of loops like this:
535 // // from src/test/compile-fail/borrowck-lend-flow.rs
536 // let mut v = box 3, w = box 4;
537 // let mut x = &mut w;
540 // borrow(v); //~ ERROR cannot borrow
541 // x = &mut v; // (1)
544 // Typically, we try to determine the region of a borrow from
545 // those points where it is dereferenced. In this case, one
546 // might imagine that the lifetime of `x` need only be the
547 // body of the loop. But of course this is incorrect because
548 // the pointer that is created at point (1) is consumed at
549 // point (2), meaning that it must be live across the loop
550 // iteration. The easiest way to guarantee this is to require
551 // that the lifetime of any regions that appear in a
552 // variable's type enclose at least the variable's scope.
554 let var_scope = tcx.region_maps.var_scope(id);
556 let origin = infer::BindingTypeIsNotValidAtDecl(span);
557 type_of_node_must_outlive(rcx, origin, id, ty::ReScope(var_scope));
559 let typ = rcx.resolve_node_type(id);
560 dropck::check_safety_of_destructor_if_necessary(rcx, typ, span, var_scope);
564 fn visit_expr(rcx: &mut Rcx, expr: &hir::Expr) {
565 debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
566 expr, rcx.repeating_scope);
568 // No matter what, the type of each expression must outlive the
569 // scope of that expression. This also guarantees basic WF.
570 let expr_ty = rcx.resolve_node_type(expr.id);
571 // the region corresponding to this expression
572 let expr_region = ty::ReScope(rcx.tcx().region_maps.node_extent(expr.id));
573 type_must_outlive(rcx, infer::ExprTypeIsNotInScope(expr_ty, expr.span),
574 expr_ty, expr_region);
576 let method_call = MethodCall::expr(expr.id);
577 let opt_method_callee = rcx.fcx.inh.tables.borrow().method_map.get(&method_call).cloned();
578 let has_method_map = opt_method_callee.is_some();
580 // If we are calling a method (either explicitly or via an
581 // overloaded operator), check that all of the types provided as
582 // arguments for its type parameters are well-formed, and all the regions
583 // provided as arguments outlive the call.
584 if let Some(callee) = opt_method_callee {
585 let origin = match expr.node {
586 hir::ExprMethodCall(..) =>
587 infer::ParameterOrigin::MethodCall,
588 hir::ExprUnary(op, _) if op == hir::UnDeref =>
589 infer::ParameterOrigin::OverloadedDeref,
591 infer::ParameterOrigin::OverloadedOperator
594 substs_wf_in_scope(rcx, origin, &callee.substs, expr.span, expr_region);
597 // Check any autoderefs or autorefs that appear.
598 let adjustment = rcx.fcx.inh.tables.borrow().adjustments.get(&expr.id).map(|a| a.clone());
599 if let Some(adjustment) = adjustment {
600 debug!("adjustment={:?}", adjustment);
602 adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
603 autoderefs, ref autoref, ..
605 let expr_ty = rcx.resolve_node_type(expr.id);
606 constrain_autoderefs(rcx, expr, autoderefs, expr_ty);
607 if let Some(ref autoref) = *autoref {
608 link_autoref(rcx, expr, autoderefs, autoref);
610 // Require that the resulting region encompasses
613 // FIXME(#6268) remove to support nested method calls
614 type_of_node_must_outlive(
615 rcx, infer::AutoBorrow(expr.span),
616 expr.id, expr_region);
620 adjustment::AutoObject(_, ref bounds, _, _) => {
621 // Determine if we are casting `expr` to a trait
622 // instance. If so, we have to be sure that the type
623 // of the source obeys the new region bound.
624 let source_ty = rcx.resolve_node_type(expr.id);
625 type_must_outlive(rcx, infer::RelateObjectBound(expr.span),
626 source_ty, bounds.region_bound);
632 // If necessary, constrain destructors in the unadjusted form of this
635 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
636 mc.cat_expr_unadjusted(expr)
640 check_safety_of_rvalue_destructor_if_necessary(rcx,
645 let tcx = rcx.fcx.tcx();
646 tcx.sess.delay_span_bug(expr.span, "cat_expr_unadjusted Errd");
651 // If necessary, constrain destructors in this expression. This will be
652 // the adjusted form if there is an adjustment.
654 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
659 check_safety_of_rvalue_destructor_if_necessary(rcx, head_cmt, expr.span);
662 let tcx = rcx.fcx.tcx();
663 tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
668 hir::ExprPath(..) => {
669 rcx.fcx.opt_node_ty_substs(expr.id, |item_substs| {
670 let origin = infer::ParameterOrigin::Path;
671 substs_wf_in_scope(rcx, origin, &item_substs.substs, expr.span, expr_region);
675 hir::ExprCall(ref callee, ref args) => {
677 constrain_call(rcx, expr, Some(&**callee),
678 args.iter().map(|e| &**e), false);
680 constrain_callee(rcx, callee.id, expr, &**callee);
681 constrain_call(rcx, expr, None,
682 args.iter().map(|e| &**e), false);
685 visit::walk_expr(rcx, expr);
688 hir::ExprMethodCall(_, _, ref args) => {
689 constrain_call(rcx, expr, Some(&*args[0]),
690 args[1..].iter().map(|e| &**e), false);
692 visit::walk_expr(rcx, expr);
695 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
697 constrain_call(rcx, expr, Some(&**lhs),
698 Some(&**rhs).into_iter(), false);
701 visit::walk_expr(rcx, expr);
704 hir::ExprIndex(ref lhs, ref rhs) if has_method_map => {
705 constrain_call(rcx, expr, Some(&**lhs),
706 Some(&**rhs).into_iter(), true);
708 visit::walk_expr(rcx, expr);
711 hir::ExprBinary(op, ref lhs, ref rhs) if has_method_map => {
712 let implicitly_ref_args = !hir_util::is_by_value_binop(op.node);
714 // As `expr_method_call`, but the call is via an
715 // overloaded op. Note that we (sadly) currently use an
716 // implicit "by ref" sort of passing style here. This
717 // should be converted to an adjustment!
718 constrain_call(rcx, expr, Some(&**lhs),
719 Some(&**rhs).into_iter(), implicitly_ref_args);
721 visit::walk_expr(rcx, expr);
724 hir::ExprBinary(_, ref lhs, ref rhs) => {
725 // If you do `x OP y`, then the types of `x` and `y` must
726 // outlive the operation you are performing.
727 let lhs_ty = rcx.resolve_expr_type_adjusted(&**lhs);
728 let rhs_ty = rcx.resolve_expr_type_adjusted(&**rhs);
729 for &ty in &[lhs_ty, rhs_ty] {
730 type_must_outlive(rcx,
731 infer::Operand(expr.span),
735 visit::walk_expr(rcx, expr);
738 hir::ExprUnary(op, ref lhs) if has_method_map => {
739 let implicitly_ref_args = !hir_util::is_by_value_unop(op);
742 constrain_call(rcx, expr, Some(&**lhs),
743 None::<hir::Expr>.iter(), implicitly_ref_args);
745 visit::walk_expr(rcx, expr);
748 hir::ExprUnary(hir::UnDeref, ref base) => {
749 // For *a, the lifetime of a must enclose the deref
750 let method_call = MethodCall::expr(expr.id);
751 let base_ty = match rcx.fcx.inh.tables.borrow().method_map.get(&method_call) {
753 constrain_call(rcx, expr, Some(&**base),
754 None::<hir::Expr>.iter(), true);
755 let fn_ret = // late-bound regions in overloaded method calls are instantiated
756 rcx.tcx().no_late_bound_regions(&method.ty.fn_ret()).unwrap();
759 None => rcx.resolve_node_type(base.id)
761 if let ty::TyRef(r_ptr, _) = base_ty.sty {
762 mk_subregion_due_to_dereference(
763 rcx, expr.span, expr_region, *r_ptr);
766 visit::walk_expr(rcx, expr);
769 hir::ExprIndex(ref vec_expr, _) => {
770 // For a[b], the lifetime of a must enclose the deref
771 let vec_type = rcx.resolve_expr_type_adjusted(&**vec_expr);
772 constrain_index(rcx, expr, vec_type);
774 visit::walk_expr(rcx, expr);
777 hir::ExprCast(ref source, _) => {
778 // Determine if we are casting `source` to a trait
779 // instance. If so, we have to be sure that the type of
780 // the source obeys the trait's region bound.
781 constrain_cast(rcx, expr, &**source);
782 visit::walk_expr(rcx, expr);
785 hir::ExprAddrOf(m, ref base) => {
786 link_addr_of(rcx, expr, m, &**base);
788 // Require that when you write a `&expr` expression, the
789 // resulting pointer has a lifetime that encompasses the
790 // `&expr` expression itself. Note that we constraining
791 // the type of the node expr.id here *before applying
794 // FIXME(#6268) nested method calls requires that this rule change
795 let ty0 = rcx.resolve_node_type(expr.id);
796 type_must_outlive(rcx, infer::AddrOf(expr.span), ty0, expr_region);
797 visit::walk_expr(rcx, expr);
800 hir::ExprMatch(ref discr, ref arms, _) => {
801 link_match(rcx, &**discr, &arms[..]);
803 visit::walk_expr(rcx, expr);
806 hir::ExprClosure(_, _, ref body) => {
807 check_expr_fn_block(rcx, expr, &**body);
810 hir::ExprLoop(ref body, _) => {
811 let repeating_scope = rcx.set_repeating_scope(body.id);
812 visit::walk_expr(rcx, expr);
813 rcx.set_repeating_scope(repeating_scope);
816 hir::ExprWhile(ref cond, ref body, _) => {
817 let repeating_scope = rcx.set_repeating_scope(cond.id);
818 rcx.visit_expr(&**cond);
820 rcx.set_repeating_scope(body.id);
821 rcx.visit_block(&**body);
823 rcx.set_repeating_scope(repeating_scope);
827 visit::walk_expr(rcx, expr);
832 fn constrain_cast(rcx: &mut Rcx,
833 cast_expr: &hir::Expr,
834 source_expr: &hir::Expr)
836 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
840 let source_ty = rcx.resolve_node_type(source_expr.id);
841 let target_ty = rcx.resolve_node_type(cast_expr.id);
843 walk_cast(rcx, cast_expr, source_ty, target_ty);
845 fn walk_cast<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
846 cast_expr: &hir::Expr,
849 debug!("walk_cast(from_ty={:?}, to_ty={:?})",
852 match (&from_ty.sty, &to_ty.sty) {
853 /*From:*/ (&ty::TyRef(from_r, ref from_mt),
854 /*To: */ &ty::TyRef(to_r, ref to_mt)) => {
855 // Target cannot outlive source, naturally.
856 rcx.fcx.mk_subr(infer::Reborrow(cast_expr.span), *to_r, *from_r);
857 walk_cast(rcx, cast_expr, from_mt.ty, to_mt.ty);
861 /*To: */ &ty::TyTrait(box ty::TraitTy { ref bounds, .. })) => {
862 // When T is existentially quantified as a trait
863 // `Foo+'to`, it must outlive the region bound `'to`.
864 type_must_outlive(rcx, infer::RelateObjectBound(cast_expr.span),
865 from_ty, bounds.region_bound);
868 /*From:*/ (&ty::TyBox(from_referent_ty),
869 /*To: */ &ty::TyBox(to_referent_ty)) => {
870 walk_cast(rcx, cast_expr, from_referent_ty, to_referent_ty);
878 fn check_expr_fn_block(rcx: &mut Rcx,
881 let repeating_scope = rcx.set_repeating_scope(body.id);
882 visit::walk_expr(rcx, expr);
883 rcx.set_repeating_scope(repeating_scope);
886 fn constrain_callee(rcx: &mut Rcx,
887 callee_id: ast::NodeId,
888 _call_expr: &hir::Expr,
889 _callee_expr: &hir::Expr) {
890 let callee_ty = rcx.resolve_node_type(callee_id);
891 match callee_ty.sty {
892 ty::TyBareFn(..) => { }
894 // this should not happen, but it does if the program is
897 // tcx.sess.span_bug(
899 // format!("Calling non-function: {}", callee_ty));
904 fn constrain_call<'a, I: Iterator<Item=&'a hir::Expr>>(rcx: &mut Rcx,
905 call_expr: &hir::Expr,
906 receiver: Option<&hir::Expr>,
908 implicitly_ref_args: bool) {
909 //! Invoked on every call site (i.e., normal calls, method calls,
910 //! and overloaded operators). Constrains the regions which appear
911 //! in the type of the function. Also constrains the regions that
912 //! appear in the arguments appropriately.
914 debug!("constrain_call(call_expr={:?}, \
916 implicitly_ref_args={})",
919 implicitly_ref_args);
921 // `callee_region` is the scope representing the time in which the
924 // FIXME(#6268) to support nested method calls, should be callee_id
925 let callee_scope = rcx.tcx().region_maps.node_extent(call_expr.id);
926 let callee_region = ty::ReScope(callee_scope);
928 debug!("callee_region={:?}", callee_region);
930 for arg_expr in arg_exprs {
931 debug!("Argument: {:?}", arg_expr);
933 // ensure that any regions appearing in the argument type are
934 // valid for at least the lifetime of the function:
935 type_of_node_must_outlive(
936 rcx, infer::CallArg(arg_expr.span),
937 arg_expr.id, callee_region);
939 // unfortunately, there are two means of taking implicit
940 // references, and we need to propagate constraints as a
941 // result. modes are going away and the "DerefArgs" code
942 // should be ported to use adjustments
943 if implicitly_ref_args {
944 link_by_ref(rcx, arg_expr, callee_scope);
948 // as loop above, but for receiver
949 if let Some(r) = receiver {
950 debug!("receiver: {:?}", r);
951 type_of_node_must_outlive(
952 rcx, infer::CallRcvr(r.span),
953 r.id, callee_region);
954 if implicitly_ref_args {
955 link_by_ref(rcx, &*r, callee_scope);
960 /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being
961 /// dereferenced, the lifetime of the pointer includes the deref expr.
962 fn constrain_autoderefs<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
963 deref_expr: &hir::Expr,
965 mut derefd_ty: Ty<'tcx>)
967 debug!("constrain_autoderefs(deref_expr={:?}, derefs={}, derefd_ty={:?})",
972 let s_deref_expr = rcx.tcx().region_maps.node_extent(deref_expr.id);
973 let r_deref_expr = ty::ReScope(s_deref_expr);
975 let method_call = MethodCall::autoderef(deref_expr.id, i as u32);
976 debug!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call, derefs);
978 let method = rcx.fcx.inh.tables.borrow().method_map.get(&method_call).map(|m| m.clone());
980 derefd_ty = match method {
982 debug!("constrain_autoderefs: #{} is overloaded, method={:?}",
985 let origin = infer::ParameterOrigin::OverloadedDeref;
986 substs_wf_in_scope(rcx, origin, method.substs, deref_expr.span, r_deref_expr);
988 // Treat overloaded autoderefs as if an AutoRef adjustment
989 // was applied on the base type, as that is always the case.
990 let fn_sig = method.ty.fn_sig();
991 let fn_sig = // late-bound regions should have been instantiated
992 rcx.tcx().no_late_bound_regions(fn_sig).unwrap();
993 let self_ty = fn_sig.inputs[0];
994 let (m, r) = match self_ty.sty {
995 ty::TyRef(r, ref m) => (m.mutbl, r),
997 rcx.tcx().sess.span_bug(
999 &format!("bad overloaded deref type {:?}",
1004 debug!("constrain_autoderefs: receiver r={:?} m={:?}",
1008 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1009 let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i));
1010 debug!("constrain_autoderefs: self_cmt={:?}",
1012 link_region(rcx, deref_expr.span, r,
1013 ty::BorrowKind::from_mutbl(m), self_cmt);
1016 // Specialized version of constrain_call.
1017 type_must_outlive(rcx, infer::CallRcvr(deref_expr.span),
1018 self_ty, r_deref_expr);
1019 match fn_sig.output {
1020 ty::FnConverging(return_type) => {
1021 type_must_outlive(rcx, infer::CallReturn(deref_expr.span),
1022 return_type, r_deref_expr);
1025 ty::FnDiverging => unreachable!()
1031 if let ty::TyRef(r_ptr, _) = derefd_ty.sty {
1032 mk_subregion_due_to_dereference(rcx, deref_expr.span,
1033 r_deref_expr, *r_ptr);
1036 match derefd_ty.builtin_deref(true, ty::NoPreference) {
1037 Some(mt) => derefd_ty = mt.ty,
1038 /* if this type can't be dereferenced, then there's already an error
1039 in the session saying so. Just bail out for now */
1045 pub fn mk_subregion_due_to_dereference(rcx: &mut Rcx,
1047 minimum_lifetime: ty::Region,
1048 maximum_lifetime: ty::Region) {
1049 rcx.fcx.mk_subr(infer::DerefPointer(deref_span),
1050 minimum_lifetime, maximum_lifetime)
1053 fn check_safety_of_rvalue_destructor_if_necessary<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
1057 mc::cat_rvalue(region) => {
1059 ty::ReScope(rvalue_scope) => {
1060 let typ = rcx.resolve_type(cmt.ty);
1061 dropck::check_safety_of_destructor_if_necessary(rcx,
1071 &format!("unexpected rvalue region in rvalue \
1072 destructor safety checking: `{:?}`",
1081 /// Invoked on any index expression that occurs. Checks that if this is a slice being indexed, the
1082 /// lifetime of the pointer includes the deref expr.
1083 fn constrain_index<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
1084 index_expr: &hir::Expr,
1085 indexed_ty: Ty<'tcx>)
1087 debug!("constrain_index(index_expr=?, indexed_ty={}",
1088 rcx.fcx.infcx().ty_to_string(indexed_ty));
1090 let r_index_expr = ty::ReScope(rcx.tcx().region_maps.node_extent(index_expr.id));
1091 if let ty::TyRef(r_ptr, mt) = indexed_ty.sty {
1093 ty::TySlice(_) | ty::TyStr => {
1094 rcx.fcx.mk_subr(infer::IndexSlice(index_expr.span),
1095 r_index_expr, *r_ptr);
1102 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1103 /// adjustments) are valid for at least `minimum_lifetime`
1104 fn type_of_node_must_outlive<'a, 'tcx>(
1105 rcx: &mut Rcx<'a, 'tcx>,
1106 origin: infer::SubregionOrigin<'tcx>,
1108 minimum_lifetime: ty::Region)
1110 let tcx = rcx.fcx.tcx();
1112 // Try to resolve the type. If we encounter an error, then typeck
1113 // is going to fail anyway, so just stop here and let typeck
1114 // report errors later on in the writeback phase.
1115 let ty0 = rcx.resolve_node_type(id);
1116 let ty = ty0.adjust(tcx, origin.span(), id,
1117 rcx.fcx.inh.tables.borrow().adjustments.get(&id),
1118 |method_call| rcx.resolve_method_type(method_call));
1119 debug!("constrain_regions_in_type_of_node(\
1120 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
1122 id, minimum_lifetime);
1123 type_must_outlive(rcx, origin, ty, minimum_lifetime);
1126 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1127 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1128 fn link_addr_of(rcx: &mut Rcx, expr: &hir::Expr,
1129 mutability: hir::Mutability, base: &hir::Expr) {
1130 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
1133 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1134 ignore_err!(mc.cat_expr(base))
1137 debug!("link_addr_of: cmt={:?}", cmt);
1139 link_region_from_node_type(rcx, expr.span, expr.id, mutability, cmt);
1142 /// Computes the guarantors for any ref bindings in a `let` and
1143 /// then ensures that the lifetime of the resulting pointer is
1144 /// linked to the lifetime of the initialization expression.
1145 fn link_local(rcx: &Rcx, local: &hir::Local) {
1146 debug!("regionck::for_local()");
1147 let init_expr = match local.init {
1149 Some(ref expr) => &**expr,
1151 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1152 let discr_cmt = ignore_err!(mc.cat_expr(init_expr));
1153 link_pattern(rcx, mc, discr_cmt, &*local.pat);
1156 /// Computes the guarantors for any ref bindings in a match and
1157 /// then ensures that the lifetime of the resulting pointer is
1158 /// linked to the lifetime of its guarantor (if any).
1159 fn link_match(rcx: &Rcx, discr: &hir::Expr, arms: &[hir::Arm]) {
1160 debug!("regionck::for_match()");
1161 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1162 let discr_cmt = ignore_err!(mc.cat_expr(discr));
1163 debug!("discr_cmt={:?}", discr_cmt);
1165 for root_pat in &arm.pats {
1166 link_pattern(rcx, mc, discr_cmt.clone(), &**root_pat);
1171 /// Computes the guarantors for any ref bindings in a match and
1172 /// then ensures that the lifetime of the resulting pointer is
1173 /// linked to the lifetime of its guarantor (if any).
1174 fn link_fn_args(rcx: &Rcx, body_scope: CodeExtent, args: &[hir::Arg]) {
1175 debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1176 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1178 let arg_ty = rcx.fcx.node_ty(arg.id);
1179 let re_scope = ty::ReScope(body_scope);
1180 let arg_cmt = mc.cat_rvalue(arg.id, arg.ty.span, re_scope, arg_ty);
1181 debug!("arg_ty={:?} arg_cmt={:?}",
1184 link_pattern(rcx, mc, arg_cmt, &*arg.pat);
1188 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found in the discriminant, if
1190 fn link_pattern<'t, 'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1191 mc: mc::MemCategorizationContext<'t, 'a, 'tcx>,
1192 discr_cmt: mc::cmt<'tcx>,
1193 root_pat: &hir::Pat) {
1194 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1197 let _ = mc.cat_pattern(discr_cmt, root_pat, |mc, sub_cmt, sub_pat| {
1198 match sub_pat.node {
1200 hir::PatIdent(hir::BindByRef(mutbl), _, _) => {
1201 link_region_from_node_type(
1202 rcx, sub_pat.span, sub_pat.id,
1206 // `[_, ..slice, _]` pattern
1207 hir::PatVec(_, Some(ref slice_pat), _) => {
1208 match mc.cat_slice_pattern(sub_cmt, &**slice_pat) {
1209 Ok((slice_cmt, slice_mutbl, slice_r)) => {
1210 link_region(rcx, sub_pat.span, &slice_r,
1211 ty::BorrowKind::from_mutbl(slice_mutbl),
1222 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1224 fn link_autoref(rcx: &Rcx,
1227 autoref: &adjustment::AutoRef)
1229 debug!("link_autoref(autoref={:?})", autoref);
1230 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1231 let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs));
1232 debug!("expr_cmt={:?}", expr_cmt);
1235 adjustment::AutoPtr(r, m) => {
1236 link_region(rcx, expr.span, r,
1237 ty::BorrowKind::from_mutbl(m), expr_cmt);
1240 adjustment::AutoUnsafe(m) => {
1241 let r = ty::ReScope(rcx.tcx().region_maps.node_extent(expr.id));
1242 link_region(rcx, expr.span, &r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1247 /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and
1248 /// must outlive `callee_scope`.
1249 fn link_by_ref(rcx: &Rcx,
1251 callee_scope: CodeExtent) {
1252 debug!("link_by_ref(expr={:?}, callee_scope={:?})",
1253 expr, callee_scope);
1254 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1255 let expr_cmt = ignore_err!(mc.cat_expr(expr));
1256 let borrow_region = ty::ReScope(callee_scope);
1257 link_region(rcx, expr.span, &borrow_region, ty::ImmBorrow, expr_cmt);
1260 /// Like `link_region()`, except that the region is extracted from the type of `id`, which must be
1261 /// some reference (`&T`, `&str`, etc).
1262 fn link_region_from_node_type<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1265 mutbl: hir::Mutability,
1266 cmt_borrowed: mc::cmt<'tcx>) {
1267 debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1268 id, mutbl, cmt_borrowed);
1270 let rptr_ty = rcx.resolve_node_type(id);
1271 if let ty::TyRef(&r, _) = rptr_ty.sty {
1272 debug!("rptr_ty={}", rptr_ty);
1273 link_region(rcx, span, &r, ty::BorrowKind::from_mutbl(mutbl),
1278 /// Informs the inference engine that `borrow_cmt` is being borrowed with kind `borrow_kind` and
1279 /// lifetime `borrow_region`. In order to ensure borrowck is satisfied, this may create constraints
1280 /// between regions, as explained in `link_reborrowed_region()`.
1281 fn link_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1283 borrow_region: &ty::Region,
1284 borrow_kind: ty::BorrowKind,
1285 borrow_cmt: mc::cmt<'tcx>) {
1286 let mut borrow_cmt = borrow_cmt;
1287 let mut borrow_kind = borrow_kind;
1289 let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1290 type_must_outlive(rcx, origin, borrow_cmt.ty, *borrow_region);
1293 debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1297 match borrow_cmt.cat.clone() {
1298 mc::cat_deref(ref_cmt, _,
1299 mc::Implicit(ref_kind, ref_region)) |
1300 mc::cat_deref(ref_cmt, _,
1301 mc::BorrowedPtr(ref_kind, ref_region)) => {
1302 match link_reborrowed_region(rcx, span,
1303 borrow_region, borrow_kind,
1304 ref_cmt, ref_region, ref_kind,
1316 mc::cat_downcast(cmt_base, _) |
1317 mc::cat_deref(cmt_base, _, mc::Unique) |
1318 mc::cat_interior(cmt_base, _) => {
1319 // Borrowing interior or owned data requires the base
1320 // to be valid and borrowable in the same fashion.
1321 borrow_cmt = cmt_base;
1322 borrow_kind = borrow_kind;
1325 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
1326 mc::cat_static_item |
1329 mc::cat_rvalue(..) => {
1330 // These are all "base cases" with independent lifetimes
1331 // that are not subject to inference
1338 /// This is the most complicated case: the path being borrowed is
1339 /// itself the referent of a borrowed pointer. Let me give an
1340 /// example fragment of code to make clear(er) the situation:
1342 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1344 /// &'z *r // the reborrow has lifetime 'z
1346 /// Now, in this case, our primary job is to add the inference
1347 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1348 /// parameters in (roughly) terms of the example:
1350 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1351 /// borrow_region ^~ ref_region ^~
1352 /// borrow_kind ^~ ref_kind ^~
1355 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1357 /// Unfortunately, there are some complications beyond the simple
1358 /// scenario I just painted:
1360 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1361 /// case, we have two jobs. First, we are inferring whether this reference
1362 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1363 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1364 /// then `r` must be an `&mut` reference). Second, whenever we link
1365 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1366 /// case we adjust the cause to indicate that the reference being
1367 /// "reborrowed" is itself an upvar. This provides a nicer error message
1368 /// should something go wrong.
1370 /// 2. There may in fact be more levels of reborrowing. In the
1371 /// example, I said the borrow was like `&'z *r`, but it might
1372 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1373 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1374 /// and `'z <= 'b`. This is explained more below.
1376 /// The return value of this function indicates whether we need to
1377 /// recurse and process `ref_cmt` (see case 2 above).
1378 fn link_reborrowed_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1380 borrow_region: &ty::Region,
1381 borrow_kind: ty::BorrowKind,
1382 ref_cmt: mc::cmt<'tcx>,
1383 ref_region: ty::Region,
1384 mut ref_kind: ty::BorrowKind,
1386 -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1388 // Possible upvar ID we may need later to create an entry in the
1391 // Detect by-ref upvar `x`:
1392 let cause = match note {
1393 mc::NoteUpvarRef(ref upvar_id) => {
1394 let upvar_capture_map = &rcx.fcx.inh.tables.borrow_mut().upvar_capture_map;
1395 match upvar_capture_map.get(upvar_id) {
1396 Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1397 // The mutability of the upvar may have been modified
1398 // by the above adjustment, so update our local variable.
1399 ref_kind = upvar_borrow.kind;
1401 infer::ReborrowUpvar(span, *upvar_id)
1404 rcx.tcx().sess.span_bug(
1406 &format!("Illegal upvar id: {:?}",
1411 mc::NoteClosureEnv(ref upvar_id) => {
1412 // We don't have any mutability changes to propagate, but
1413 // we do want to note that an upvar reborrow caused this
1415 infer::ReborrowUpvar(span, *upvar_id)
1418 infer::Reborrow(span)
1422 debug!("link_reborrowed_region: {:?} <= {:?}",
1425 rcx.fcx.mk_subr(cause, *borrow_region, ref_region);
1427 // If we end up needing to recurse and establish a region link
1428 // with `ref_cmt`, calculate what borrow kind we will end up
1429 // needing. This will be used below.
1431 // One interesting twist is that we can weaken the borrow kind
1432 // when we recurse: to reborrow an `&mut` referent as mutable,
1433 // borrowck requires a unique path to the `&mut` reference but not
1434 // necessarily a *mutable* path.
1435 let new_borrow_kind = match borrow_kind {
1438 ty::MutBorrow | ty::UniqueImmBorrow =>
1442 // Decide whether we need to recurse and link any regions within
1443 // the `ref_cmt`. This is concerned for the case where the value
1444 // being reborrowed is in fact a borrowed pointer found within
1445 // another borrowed pointer. For example:
1447 // let p: &'b &'a mut T = ...;
1451 // What makes this case particularly tricky is that, if the data
1452 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1453 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1454 // (otherwise the user might mutate through the `&mut T` reference
1455 // after `'b` expires and invalidate the borrow we are looking at
1458 // So let's re-examine our parameters in light of this more
1459 // complicated (possible) scenario:
1461 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1462 // borrow_region ^~ ref_region ^~
1463 // borrow_kind ^~ ref_kind ^~
1466 // (Note that since we have not examined `ref_cmt.cat`, we don't
1467 // know whether this scenario has occurred; but I wanted to show
1468 // how all the types get adjusted.)
1471 // The reference being reborrowed is a sharable ref of
1472 // type `&'a T`. In this case, it doesn't matter where we
1473 // *found* the `&T` pointer, the memory it references will
1474 // be valid and immutable for `'a`. So we can stop here.
1476 // (Note that the `borrow_kind` must also be ImmBorrow or
1477 // else the user is borrowed imm memory as mut memory,
1478 // which means they'll get an error downstream in borrowck
1483 ty::MutBorrow | ty::UniqueImmBorrow => {
1484 // The reference being reborrowed is either an `&mut T` or
1485 // `&uniq T`. This is the case where recursion is needed.
1486 return Some((ref_cmt, new_borrow_kind));
1491 /// Checks that the values provided for type/region arguments in a given
1492 /// expression are well-formed and in-scope.
1493 pub fn substs_wf_in_scope<'a,'tcx>(rcx: &mut Rcx<'a,'tcx>,
1494 origin: infer::ParameterOrigin,
1495 substs: &Substs<'tcx>,
1497 expr_region: ty::Region) {
1498 debug!("substs_wf_in_scope(substs={:?}, \
1502 substs, expr_region, origin, expr_span);
1504 let origin = infer::ParameterInScope(origin, expr_span);
1506 for ®ion in substs.regions() {
1507 rcx.fcx.mk_subr(origin.clone(), expr_region, region);
1510 for &ty in &substs.types {
1511 let ty = rcx.resolve_type(ty);
1512 type_must_outlive(rcx, origin.clone(), ty, expr_region);
1516 /// Ensures that type is well-formed in `region`, which implies (among
1517 /// other things) that all borrowed data reachable via `ty` outlives
1519 pub fn type_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1520 origin: infer::SubregionOrigin<'tcx>,
1524 let ty = rcx.resolve_type(ty);
1526 debug!("type_must_outlive(ty={:?}, region={:?})",
1530 assert!(!ty.has_escaping_regions());
1532 let components = ty::outlives::components(rcx.infcx(), ty);
1533 components_must_outlive(rcx, origin, components, region);
1536 fn components_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1537 origin: infer::SubregionOrigin<'tcx>,
1538 components: Vec<ty::outlives::Component<'tcx>>,
1541 for component in components {
1542 let origin = origin.clone();
1544 ty::outlives::Component::Region(region1) => {
1545 rcx.fcx.mk_subr(origin, region, region1);
1547 ty::outlives::Component::Param(param_ty) => {
1548 param_ty_must_outlive(rcx, origin, region, param_ty);
1550 ty::outlives::Component::Projection(projection_ty) => {
1551 projection_must_outlive(rcx, origin, region, projection_ty);
1553 ty::outlives::Component::EscapingProjection(subcomponents) => {
1554 components_must_outlive(rcx, origin, subcomponents, region);
1556 ty::outlives::Component::UnresolvedInferenceVariable(v) => {
1557 // ignore this, we presume it will yield an error
1558 // later, since if a type variable is not resolved by
1559 // this point it never will be
1560 rcx.tcx().sess.delay_span_bug(
1562 &format!("unresolved inference variable in outlives: {:?}", v));
1564 ty::outlives::Component::RFC1214(subcomponents) => {
1565 let suborigin = infer::RFC1214Subregion(Rc::new(origin));
1566 components_must_outlive(rcx, suborigin, subcomponents, region);
1572 fn param_ty_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1573 origin: infer::SubregionOrigin<'tcx>,
1575 param_ty: ty::ParamTy) {
1576 debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1577 region, param_ty, origin);
1579 let verify_bound = param_bound(rcx, param_ty);
1580 let generic = GenericKind::Param(param_ty);
1581 rcx.fcx.infcx().verify_generic_bound(origin, generic, region, verify_bound);
1584 fn projection_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1585 origin: infer::SubregionOrigin<'tcx>,
1587 projection_ty: ty::ProjectionTy<'tcx>)
1589 debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1590 region, projection_ty, origin);
1592 // This case is thorny for inference. The fundamental problem is
1593 // that there are many cases where we have choice, and inference
1594 // doesn't like choice (the current region inference in
1595 // particular). :) First off, we have to choose between using the
1596 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1597 // OutlivesProjectionComponent rules, any one of which is
1598 // sufficient. If there are no inference variables involved, it's
1599 // not hard to pick the right rule, but if there are, we're in a
1600 // bit of a catch 22: if we picked which rule we were going to
1601 // use, we could add constraints to the region inference graph
1602 // that make it apply, but if we don't add those constraints, the
1603 // rule might not apply (but another rule might). For now, we err
1604 // on the side of adding too few edges into the graph.
1606 // Compute the bounds we can derive from the environment or trait
1607 // definition. We know that the projection outlives all the
1608 // regions in this list.
1609 let env_bounds = projection_declared_bounds(rcx, origin.span(), projection_ty);
1611 debug!("projection_must_outlive: env_bounds={:?}",
1614 // If we know that the projection outlives 'static, then we're
1616 if env_bounds.contains(&ty::ReStatic) {
1617 debug!("projection_must_outlive: 'static as declared bound");
1621 // If declared bounds list is empty, the only applicable rule is
1622 // OutlivesProjectionComponent. If there are inference variables,
1623 // then, we can break down the outlives into more primitive
1624 // components without adding unnecessary edges.
1626 // If there are *no* inference variables, however, we COULD do
1627 // this, but we choose not to, because the error messages are less
1628 // good. For example, a requirement like `T::Item: 'r` would be
1629 // translated to a requirement that `T: 'r`; when this is reported
1630 // to the user, it will thus say "T: 'r must hold so that T::Item:
1631 // 'r holds". But that makes it sound like the only way to fix
1632 // the problem is to add `T: 'r`, which isn't true. So, if there are no
1633 // inference variables, we use a verify constraint instead of adding
1634 // edges, which winds up enforcing the same condition.
1636 projection_ty.trait_ref.substs.types.iter().any(|t| t.needs_infer()) ||
1637 projection_ty.trait_ref.substs.regions().iter().any(|r| r.needs_infer())
1639 if env_bounds.is_empty() && needs_infer {
1640 debug!("projection_must_outlive: no declared bounds");
1642 for &component_ty in &projection_ty.trait_ref.substs.types {
1643 type_must_outlive(rcx, origin.clone(), component_ty, region);
1646 for &r in projection_ty.trait_ref.substs.regions() {
1647 rcx.fcx.mk_subr(origin.clone(), region, r);
1653 // If we find that there is a unique declared bound `'b`, and this bound
1654 // appears in the trait reference, then the best action is to require that `'b:'r`,
1655 // so do that. This is best no matter what rule we use:
1657 // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1658 // the requirement that `'b:'r`
1659 // - OutlivesProjectionComponent: this would require `'b:'r` in addition to other conditions
1660 if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) {
1661 let unique_bound = env_bounds[0];
1662 debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound);
1663 if projection_ty.trait_ref.substs.regions()
1665 .any(|r| env_bounds.contains(r))
1667 debug!("projection_must_outlive: unique declared bound appears in trait ref");
1668 rcx.fcx.mk_subr(origin.clone(), region, unique_bound);
1673 // Fallback to verifying after the fact that there exists a
1674 // declared bound, or that all the components appearing in the
1675 // projection outlive; in some cases, this may add insufficient
1676 // edges into the inference graph, leading to inference failures
1677 // even though a satisfactory solution exists.
1678 let verify_bound = projection_bound(rcx, origin.span(), env_bounds, projection_ty);
1679 let generic = GenericKind::Projection(projection_ty);
1680 rcx.fcx.infcx().verify_generic_bound(origin, generic.clone(), region, verify_bound);
1683 fn type_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, span: Span, ty: Ty<'tcx>) -> VerifyBound {
1688 ty::TyProjection(data) => {
1689 let declared_bounds = projection_declared_bounds(rcx, span, data);
1690 projection_bound(rcx, span, declared_bounds, data)
1693 recursive_type_bound(rcx, span, ty)
1698 fn param_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, param_ty: ty::ParamTy) -> VerifyBound {
1699 let param_env = &rcx.infcx().parameter_environment;
1701 debug!("param_bound(param_ty={:?})",
1704 let mut param_bounds = declared_generic_bounds_from_env(rcx, GenericKind::Param(param_ty));
1706 // Add in the default bound of fn body that applies to all in
1707 // scope type parameters:
1708 param_bounds.push(param_env.implicit_region_bound);
1710 VerifyBound::AnyRegion(param_bounds)
1713 fn projection_declared_bounds<'a, 'tcx>(rcx: &Rcx<'a,'tcx>,
1715 projection_ty: ty::ProjectionTy<'tcx>)
1718 // First assemble bounds from where clauses and traits.
1720 let mut declared_bounds =
1721 declared_generic_bounds_from_env(rcx, GenericKind::Projection(projection_ty));
1723 declared_bounds.push_all(
1724 &declared_projection_bounds_from_trait(rcx, span, projection_ty));
1729 fn projection_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1731 declared_bounds: Vec<ty::Region>,
1732 projection_ty: ty::ProjectionTy<'tcx>)
1734 debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1735 declared_bounds, projection_ty);
1737 // see the extensive comment in projection_must_outlive
1739 let ty = rcx.tcx().mk_projection(projection_ty.trait_ref, projection_ty.item_name);
1740 let recursive_bound = recursive_type_bound(rcx, span, ty);
1742 VerifyBound::AnyRegion(declared_bounds).or(recursive_bound)
1745 fn recursive_type_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1749 let mut bounds = vec![];
1751 for subty in ty.walk_shallow() {
1752 bounds.push(type_bound(rcx, span, subty));
1755 let mut regions = ty.regions();
1756 regions.retain(|r| !r.is_bound()); // ignore late-bound regions
1757 bounds.push(VerifyBound::AllRegions(regions));
1759 // remove bounds that must hold, since they are not interesting
1760 bounds.retain(|b| !b.must_hold());
1762 if bounds.len() == 1 {
1763 bounds.pop().unwrap()
1765 VerifyBound::AllBounds(bounds)
1769 fn declared_generic_bounds_from_env<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1770 generic: GenericKind<'tcx>)
1773 let param_env = &rcx.infcx().parameter_environment;
1775 // To start, collect bounds from user:
1776 let mut param_bounds = rcx.tcx().required_region_bounds(generic.to_ty(rcx.tcx()),
1777 param_env.caller_bounds.clone());
1779 // Next, collect regions we scraped from the well-formedness
1780 // constraints in the fn signature. To do that, we walk the list
1781 // of known relations from the fn ctxt.
1783 // This is crucial because otherwise code like this fails:
1785 // fn foo<'a, A>(x: &'a A) { x.bar() }
1787 // The problem is that the type of `x` is `&'a A`. To be
1788 // well-formed, then, A must be lower-generic by `'a`, but we
1789 // don't know that this holds from first principles.
1790 for &(r, p) in &rcx.region_bound_pairs {
1791 debug!("generic={:?} p={:?}",
1795 param_bounds.push(r);
1802 fn declared_projection_bounds_from_trait<'a,'tcx>(rcx: &Rcx<'a, 'tcx>,
1804 projection_ty: ty::ProjectionTy<'tcx>)
1808 let tcx = fcx.tcx();
1809 let infcx = fcx.infcx();
1811 debug!("projection_bounds(projection_ty={:?})",
1814 let ty = tcx.mk_projection(projection_ty.trait_ref.clone(), projection_ty.item_name);
1816 // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1817 // in looking for a trait definition like:
1820 // trait SomeTrait<'a> {
1821 // type SomeType : 'a;
1825 // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1826 let trait_predicates = tcx.lookup_predicates(projection_ty.trait_ref.def_id);
1827 let predicates = trait_predicates.predicates.as_slice().to_vec();
1828 traits::elaborate_predicates(tcx, predicates)
1829 .filter_map(|predicate| {
1830 // we're only interesting in `T : 'a` style predicates:
1831 let outlives = match predicate {
1832 ty::Predicate::TypeOutlives(data) => data,
1833 _ => { return None; }
1836 debug!("projection_bounds: outlives={:?} (1)",
1839 // apply the substitutions (and normalize any projected types)
1840 let outlives = fcx.instantiate_type_scheme(span,
1841 projection_ty.trait_ref.substs,
1844 debug!("projection_bounds: outlives={:?} (2)",
1847 let region_result = infcx.commit_if_ok(|_| {
1849 infcx.replace_late_bound_regions_with_fresh_var(
1851 infer::AssocTypeProjection(projection_ty.item_name),
1854 debug!("projection_bounds: outlives={:?} (3)",
1857 // check whether this predicate applies to our current projection
1858 match infer::mk_eqty(infcx, false, infer::Misc(span), ty, outlives.0) {
1859 Ok(()) => { Ok(outlives.1) }
1860 Err(_) => { Err(()) }
1864 debug!("projection_bounds: region_result={:?}",