1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The region check is a final pass that runs over the AST after we have
12 //! inferred the type constraints but before we have actually finalized
13 //! the types. Its purpose is to embed a variety of region constraints.
14 //! Inserting these constraints as a separate pass is good because (1) it
15 //! localizes the code that has to do with region inference and (2) often
16 //! we cannot know what constraints are needed until the basic types have
19 //! ### Interaction with the borrow checker
21 //! In general, the job of the borrowck module (which runs later) is to
22 //! check that all soundness criteria are met, given a particular set of
23 //! regions. The job of *this* module is to anticipate the needs of the
24 //! borrow checker and infer regions that will satisfy its requirements.
25 //! It is generally true that the inference doesn't need to be sound,
26 //! meaning that if there is a bug and we inferred bad regions, the borrow
27 //! checker should catch it. This is not entirely true though; for
28 //! example, the borrow checker doesn't check subtyping, and it doesn't
29 //! check that region pointers are always live when they are used. It
30 //! might be worthwhile to fix this so that borrowck serves as a kind of
31 //! verification step -- that would add confidence in the overall
32 //! correctness of the compiler, at the cost of duplicating some type
33 //! checks and effort.
35 //! ### Inferring the duration of borrows, automatic and otherwise
37 //! Whenever we introduce a borrowed pointer, for example as the result of
38 //! a borrow expression `let x = &data`, the lifetime of the pointer `x`
39 //! is always specified as a region inference variable. `regionck` has the
40 //! job of adding constraints such that this inference variable is as
41 //! narrow as possible while still accommodating all uses (that is, every
42 //! dereference of the resulting pointer must be within the lifetime).
46 //! Generally speaking, `regionck` does NOT try to ensure that the data
47 //! `data` will outlive the pointer `x`. That is the job of borrowck. The
48 //! one exception is when "re-borrowing" the contents of another borrowed
49 //! pointer. For example, imagine you have a borrowed pointer `b` with
50 //! lifetime L1 and you have an expression `&*b`. The result of this
51 //! expression will be another borrowed pointer with lifetime L2 (which is
52 //! an inference variable). The borrow checker is going to enforce the
53 //! constraint that L2 < L1, because otherwise you are re-borrowing data
54 //! for a lifetime larger than the original loan. However, without the
55 //! routines in this module, the region inferencer would not know of this
56 //! dependency and thus it might infer the lifetime of L2 to be greater
57 //! than L1 (issue #3148).
59 //! There are a number of troublesome scenarios in the tests
60 //! `region-dependent-*.rs`, but here is one example:
62 //! struct Foo { i: i32 }
63 //! struct Bar { foo: Foo }
64 //! fn get_i<'a>(x: &'a Bar) -> &'a i32 {
65 //! let foo = &x.foo; // Lifetime L1
66 //! &foo.i // Lifetime L2
69 //! Note that this comes up either with `&` expressions, `ref`
70 //! bindings, and `autorefs`, which are the three ways to introduce
73 //! The key point here is that when you are borrowing a value that
74 //! is "guaranteed" by a borrowed pointer, you must link the
75 //! lifetime of that borrowed pointer (L1, here) to the lifetime of
76 //! the borrow itself (L2). What do I mean by "guaranteed" by a
77 //! borrowed pointer? I mean any data that is reached by first
78 //! dereferencing a borrowed pointer and then either traversing
79 //! interior offsets or boxes. We say that the guarantor
80 //! of such data is the region of the borrowed pointer that was
81 //! traversed. This is essentially the same as the ownership
82 //! relation, except that a borrowed pointer never owns its
87 use middle::free_region::FreeRegionMap;
88 use middle::mem_categorization as mc;
89 use middle::mem_categorization::Categorization;
90 use middle::region::{CodeExtent, RegionMaps};
91 use rustc::hir::def_id::DefId;
92 use rustc::ty::subst::Substs;
94 use rustc::ty::{self, Ty, MethodCall, TypeFoldable};
95 use rustc::infer::{self, GenericKind, SubregionOrigin, VerifyBound};
96 use rustc::ty::adjustment;
97 use rustc::ty::wf::ImpliedBound;
103 use syntax_pos::Span;
104 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
105 use rustc::hir::{self, PatKind};
107 // a variation on try that just returns unit
108 macro_rules! ignore_err {
109 ($e:expr) => (match $e { Ok(e) => e, Err(_) => return () })
112 ///////////////////////////////////////////////////////////////////////////
113 // PUBLIC ENTRY POINTS
115 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
116 pub fn regionck_expr(&self, body: &'gcx hir::Body) {
117 let subject = self.tcx.hir.body_owner_def_id(body.id());
118 let id = body.value.id;
119 let mut rcx = RegionCtxt::new(self, RepeatingScope(id), id, Subject(subject));
120 if self.err_count_since_creation() == 0 {
121 // regionck assumes typeck succeeded
122 rcx.visit_body(body);
123 rcx.visit_region_obligations(id);
125 rcx.resolve_regions_and_report_errors();
127 assert!(self.tables.borrow().free_region_map.is_empty());
128 self.tables.borrow_mut().free_region_map = rcx.free_region_map;
131 /// Region checking during the WF phase for items. `wf_tys` are the
132 /// types from which we should derive implied bounds, if any.
133 pub fn regionck_item(&self,
134 item_id: ast::NodeId,
136 wf_tys: &[Ty<'tcx>]) {
137 debug!("regionck_item(item.id={:?}, wf_tys={:?}", item_id, wf_tys);
138 let subject = self.tcx.hir.local_def_id(item_id);
139 let mut rcx = RegionCtxt::new(self, RepeatingScope(item_id), item_id, Subject(subject));
140 rcx.free_region_map.relate_free_regions_from_predicates(
141 &self.parameter_environment.caller_bounds);
142 rcx.relate_free_regions(wf_tys, item_id, span);
143 rcx.visit_region_obligations(item_id);
144 rcx.resolve_regions_and_report_errors();
147 pub fn regionck_fn(&self,
149 body: &'gcx hir::Body) {
150 debug!("regionck_fn(id={})", fn_id);
151 let subject = self.tcx.hir.body_owner_def_id(body.id());
152 let node_id = body.value.id;
153 let mut rcx = RegionCtxt::new(self, RepeatingScope(node_id), node_id, Subject(subject));
155 if self.err_count_since_creation() == 0 {
156 // regionck assumes typeck succeeded
157 rcx.visit_fn_body(fn_id, body, self.tcx.hir.span(fn_id));
160 rcx.free_region_map.relate_free_regions_from_predicates(
161 &self.parameter_environment.caller_bounds);
163 rcx.resolve_regions_and_report_errors();
165 // In this mode, we also copy the free-region-map into the
166 // tables of the enclosing fcx. In the other regionck modes
167 // (e.g., `regionck_item`), we don't have an enclosing tables.
168 assert!(self.tables.borrow().free_region_map.is_empty());
169 self.tables.borrow_mut().free_region_map = rcx.free_region_map;
173 ///////////////////////////////////////////////////////////////////////////
176 pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
177 pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
179 region_bound_pairs: Vec<(ty::Region<'tcx>, GenericKind<'tcx>)>,
181 pub region_maps: Rc<RegionMaps>,
183 free_region_map: FreeRegionMap<'tcx>,
185 // id of innermost fn body id
186 body_id: ast::NodeId,
188 // call_site scope of innermost fn
189 call_site_scope: Option<CodeExtent>,
191 // id of innermost fn or loop
192 repeating_scope: ast::NodeId,
194 // id of AST node being analyzed (the subject of the analysis).
195 subject_def_id: DefId,
199 impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> {
200 type Target = FnCtxt<'a, 'gcx, 'tcx>;
201 fn deref(&self) -> &Self::Target {
206 pub struct RepeatingScope(ast::NodeId);
207 pub struct Subject(DefId);
209 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
210 pub fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
211 RepeatingScope(initial_repeating_scope): RepeatingScope,
212 initial_body_id: ast::NodeId,
213 Subject(subject): Subject) -> RegionCtxt<'a, 'gcx, 'tcx> {
214 let region_maps = fcx.tcx.region_maps(subject);
217 region_maps: region_maps,
218 repeating_scope: initial_repeating_scope,
219 body_id: initial_body_id,
220 call_site_scope: None,
221 subject_def_id: subject,
222 region_bound_pairs: Vec::new(),
223 free_region_map: FreeRegionMap::new(),
227 fn set_call_site_scope(&mut self, call_site_scope: Option<CodeExtent>)
228 -> Option<CodeExtent> {
229 mem::replace(&mut self.call_site_scope, call_site_scope)
232 fn set_body_id(&mut self, body_id: ast::NodeId) -> ast::NodeId {
233 mem::replace(&mut self.body_id, body_id)
236 fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId {
237 mem::replace(&mut self.repeating_scope, scope)
240 /// Try to resolve the type for the given node, returning t_err if an error results. Note that
241 /// we never care about the details of the error, the same error will be detected and reported
242 /// in the writeback phase.
244 /// Note one important point: we do not attempt to resolve *region variables* here. This is
245 /// because regionck is essentially adding constraints to those region variables and so may yet
246 /// influence how they are resolved.
248 /// Consider this silly example:
251 /// fn borrow(x: &i32) -> &i32 {x}
252 /// fn foo(x: @i32) -> i32 { // block: B
253 /// let b = borrow(x); // region: <R0>
258 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
259 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
260 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
261 /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
262 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
263 pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
264 self.resolve_type_vars_if_possible(&unresolved_ty)
267 /// Try to resolve the type for the given node.
268 fn resolve_node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
269 let t = self.node_ty(id);
273 /// Try to resolve the type for the given node.
274 pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> {
275 let ty = self.tables.borrow().expr_ty_adjusted(expr);
276 self.resolve_type(ty)
279 fn visit_fn_body(&mut self,
280 id: ast::NodeId, // the id of the fn itself
281 body: &'gcx hir::Body,
284 // When we enter a function, we can derive
285 debug!("visit_fn_body(id={})", id);
287 let body_id = body.id();
289 let call_site = CodeExtent::CallSiteScope(body_id);
290 let old_call_site_scope = self.set_call_site_scope(Some(call_site));
293 let fn_sig_map = &self.tables.borrow().liberated_fn_sigs;
294 match fn_sig_map.get(&id) {
295 Some(f) => f.clone(),
297 bug!("No fn-sig entry for id={}", id);
302 let old_region_bounds_pairs_len = self.region_bound_pairs.len();
304 // Collect the types from which we create inferred bounds.
305 // For the return type, if diverging, substitute `bool` just
306 // because it will have no effect.
308 // FIXME(#27579) return types should not be implied bounds
309 let fn_sig_tys: Vec<_> =
310 fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
312 let old_body_id = self.set_body_id(body_id.node_id);
313 self.relate_free_regions(&fn_sig_tys[..], body_id.node_id, span);
314 self.link_fn_args(CodeExtent::Misc(body_id.node_id), &body.arguments);
315 self.visit_body(body);
316 self.visit_region_obligations(body_id.node_id);
318 let call_site_scope = self.call_site_scope.unwrap();
319 debug!("visit_fn_body body.id {:?} call_site_scope: {:?}",
320 body.id(), call_site_scope);
321 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope));
322 self.type_of_node_must_outlive(infer::CallReturn(span),
326 self.region_bound_pairs.truncate(old_region_bounds_pairs_len);
328 self.set_body_id(old_body_id);
329 self.set_call_site_scope(old_call_site_scope);
332 fn visit_region_obligations(&mut self, node_id: ast::NodeId)
334 debug!("visit_region_obligations: node_id={}", node_id);
336 // region checking can introduce new pending obligations
337 // which, when processed, might generate new region
338 // obligations. So make sure we process those.
339 self.select_all_obligations_or_error();
341 // Make a copy of the region obligations vec because we'll need
342 // to be able to borrow the fulfillment-cx below when projecting.
343 let region_obligations =
346 .region_obligations(node_id)
349 for r_o in ®ion_obligations {
350 debug!("visit_region_obligations: r_o={:?} cause={:?}",
352 let sup_type = self.resolve_type(r_o.sup_type);
353 let origin = self.code_to_origin(&r_o.cause, sup_type);
354 self.type_must_outlive(origin, sup_type, r_o.sub_region);
357 // Processing the region obligations should not cause the list to grow further:
358 assert_eq!(region_obligations.len(),
359 self.fulfillment_cx.borrow().region_obligations(node_id).len());
362 fn code_to_origin(&self,
363 cause: &traits::ObligationCause<'tcx>,
365 -> SubregionOrigin<'tcx> {
366 SubregionOrigin::from_obligation_cause(cause,
367 || infer::RelateParamBound(cause.span, sup_type))
370 /// This method populates the region map's `free_region_map`. It walks over the transformed
371 /// argument and return types for each function just before we check the body of that function,
372 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
373 /// [usize]`. We do not allow references to outlive the things they point at, so we can assume
374 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
375 /// the caller side, the caller is responsible for checking that the type of every expression
376 /// (including the actual values for the arguments, as well as the return type of the fn call)
379 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
380 fn relate_free_regions(&mut self,
381 fn_sig_tys: &[Ty<'tcx>],
382 body_id: ast::NodeId,
384 debug!("relate_free_regions >>");
386 for &ty in fn_sig_tys {
387 let ty = self.resolve_type(ty);
388 debug!("relate_free_regions(t={:?})", ty);
389 let implied_bounds = ty::wf::implied_bounds(self, body_id, ty, span);
391 // Record any relations between free regions that we observe into the free-region-map.
392 self.free_region_map.relate_free_regions_from_implied_bounds(&implied_bounds);
394 // But also record other relationships, such as `T:'x`,
395 // that don't go into the free-region-map but which we use
397 for implication in implied_bounds {
398 debug!("implication: {:?}", implication);
400 ImpliedBound::RegionSubRegion(r_a @ &ty::ReEarlyBound(_),
402 ImpliedBound::RegionSubRegion(r_a @ &ty::ReFree(_),
403 &ty::ReVar(vid_b)) => {
404 self.add_given(r_a, vid_b);
406 ImpliedBound::RegionSubParam(r_a, param_b) => {
407 self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
409 ImpliedBound::RegionSubProjection(r_a, projection_b) => {
410 self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
412 ImpliedBound::RegionSubRegion(..) => {
413 // In principle, we could record (and take
414 // advantage of) every relationship here, but
415 // we are also free not to -- it simply means
416 // strictly less that we can successfully type
417 // check. (It may also be that we should
418 // revise our inference system to be more
419 // general and to make use of *every*
420 // relationship that arises here, but
421 // presently we do not.)
427 debug!("<< relate_free_regions");
430 fn resolve_regions_and_report_errors(&self) {
431 self.fcx.resolve_regions_and_report_errors(self.subject_def_id,
433 &self.free_region_map);
436 fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) {
437 debug!("regionck::visit_pat(pat={:?})", pat);
438 pat.each_binding(|_, id, span, _| {
439 // If we have a variable that contains region'd data, that
440 // data will be accessible from anywhere that the variable is
441 // accessed. We must be wary of loops like this:
443 // // from src/test/compile-fail/borrowck-lend-flow.rs
444 // let mut v = box 3, w = box 4;
445 // let mut x = &mut w;
448 // borrow(v); //~ ERROR cannot borrow
449 // x = &mut v; // (1)
452 // Typically, we try to determine the region of a borrow from
453 // those points where it is dereferenced. In this case, one
454 // might imagine that the lifetime of `x` need only be the
455 // body of the loop. But of course this is incorrect because
456 // the pointer that is created at point (1) is consumed at
457 // point (2), meaning that it must be live across the loop
458 // iteration. The easiest way to guarantee this is to require
459 // that the lifetime of any regions that appear in a
460 // variable's type enclose at least the variable's scope.
462 let var_scope = self.region_maps.var_scope(id);
463 let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
465 let origin = infer::BindingTypeIsNotValidAtDecl(span);
466 self.type_of_node_must_outlive(origin, id, var_region);
468 let typ = self.resolve_node_type(id);
469 let _ = dropck::check_safety_of_destructor_if_necessary(
470 self, typ, span, var_scope);
475 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for RegionCtxt<'a, 'gcx, 'tcx> {
476 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
477 // However, right now we run into an issue whereby some free
478 // regions are not properly related if they appear within the
479 // types of arguments that must be inferred. This could be
480 // addressed by deferring the construction of the region
481 // hierarchy, and in particular the relationships between free
482 // regions, until regionck, as described in #3238.
484 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
485 NestedVisitorMap::None
488 fn visit_fn(&mut self, _fk: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
489 b: hir::BodyId, span: Span, id: ast::NodeId) {
490 let body = self.tcx.hir.body(b);
491 self.visit_fn_body(id, body, span)
494 //visit_pat: visit_pat, // (..) see above
496 fn visit_arm(&mut self, arm: &'gcx hir::Arm) {
499 self.constrain_bindings_in_pat(p);
501 intravisit::walk_arm(self, arm);
504 fn visit_local(&mut self, l: &'gcx hir::Local) {
506 self.constrain_bindings_in_pat(&l.pat);
508 intravisit::walk_local(self, l);
511 fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
512 debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
513 expr, self.repeating_scope);
515 // No matter what, the type of each expression must outlive the
516 // scope of that expression. This also guarantees basic WF.
517 let expr_ty = self.resolve_node_type(expr.id);
518 // the region corresponding to this expression
519 let expr_region = self.tcx.node_scope_region(expr.id);
520 self.type_must_outlive(infer::ExprTypeIsNotInScope(expr_ty, expr.span),
521 expr_ty, expr_region);
523 let method_call = MethodCall::expr(expr.id);
524 let opt_method_callee = self.tables.borrow().method_map.get(&method_call).cloned();
525 let has_method_map = opt_method_callee.is_some();
527 // If we are calling a method (either explicitly or via an
528 // overloaded operator), check that all of the types provided as
529 // arguments for its type parameters are well-formed, and all the regions
530 // provided as arguments outlive the call.
531 if let Some(callee) = opt_method_callee {
532 let origin = match expr.node {
533 hir::ExprMethodCall(..) =>
534 infer::ParameterOrigin::MethodCall,
535 hir::ExprUnary(op, _) if op == hir::UnDeref =>
536 infer::ParameterOrigin::OverloadedDeref,
538 infer::ParameterOrigin::OverloadedOperator
541 self.substs_wf_in_scope(origin, &callee.substs, expr.span, expr_region);
542 self.type_must_outlive(infer::ExprTypeIsNotInScope(callee.ty, expr.span),
543 callee.ty, expr_region);
546 // Check any autoderefs or autorefs that appear.
547 let adjustment = self.tables.borrow().adjustments.get(&expr.id).map(|a| a.clone());
548 if let Some(adjustment) = adjustment {
549 debug!("adjustment={:?}", adjustment);
550 match adjustment.kind {
551 adjustment::Adjust::DerefRef { autoderefs, ref autoref, .. } => {
552 let expr_ty = self.resolve_node_type(expr.id);
553 self.constrain_autoderefs(expr, autoderefs, expr_ty);
554 if let Some(ref autoref) = *autoref {
555 self.link_autoref(expr, autoderefs, autoref);
557 // Require that the resulting region encompasses
560 // FIXME(#6268) remove to support nested method calls
561 self.type_of_node_must_outlive(infer::AutoBorrow(expr.span),
562 expr.id, expr_region);
566 adjustment::AutoObject(_, ref bounds, ..) => {
567 // Determine if we are casting `expr` to a trait
568 // instance. If so, we have to be sure that the type
569 // of the source obeys the new region bound.
570 let source_ty = self.resolve_node_type(expr.id);
571 self.type_must_outlive(infer::RelateObjectBound(expr.span),
572 source_ty, bounds.region_bound);
578 // If necessary, constrain destructors in the unadjusted form of this
581 let mc = mc::MemCategorizationContext::new(self, &self.region_maps);
582 mc.cat_expr_unadjusted(expr)
586 self.check_safety_of_rvalue_destructor_if_necessary(head_cmt,
590 self.tcx.sess.delay_span_bug(expr.span, "cat_expr_unadjusted Errd");
595 // If necessary, constrain destructors in this expression. This will be
596 // the adjusted form if there is an adjustment.
598 let mc = mc::MemCategorizationContext::new(self, &self.region_maps);
603 self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, expr.span);
606 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
610 debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
611 expr, self.repeating_scope);
613 hir::ExprPath(_) => {
614 self.fcx.opt_node_ty_substs(expr.id, |item_substs| {
615 let origin = infer::ParameterOrigin::Path;
616 self.substs_wf_in_scope(origin, &item_substs.substs, expr.span, expr_region);
620 hir::ExprCall(ref callee, ref args) => {
622 self.constrain_call(expr, Some(&callee),
623 args.iter().map(|e| &*e), false);
625 self.constrain_callee(callee.id, expr, &callee);
626 self.constrain_call(expr, None,
627 args.iter().map(|e| &*e), false);
630 intravisit::walk_expr(self, expr);
633 hir::ExprMethodCall(.., ref args) => {
634 self.constrain_call(expr, Some(&args[0]),
635 args[1..].iter().map(|e| &*e), false);
637 intravisit::walk_expr(self, expr);
640 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
642 self.constrain_call(expr, Some(&lhs),
643 Some(&**rhs).into_iter(), false);
646 intravisit::walk_expr(self, expr);
649 hir::ExprIndex(ref lhs, ref rhs) if has_method_map => {
650 self.constrain_call(expr, Some(&lhs),
651 Some(&**rhs).into_iter(), true);
653 intravisit::walk_expr(self, expr);
656 hir::ExprBinary(op, ref lhs, ref rhs) if has_method_map => {
657 let implicitly_ref_args = !op.node.is_by_value();
659 // As `expr_method_call`, but the call is via an
660 // overloaded op. Note that we (sadly) currently use an
661 // implicit "by ref" sort of passing style here. This
662 // should be converted to an adjustment!
663 self.constrain_call(expr, Some(&lhs),
664 Some(&**rhs).into_iter(), implicitly_ref_args);
666 intravisit::walk_expr(self, expr);
669 hir::ExprBinary(_, ref lhs, ref rhs) => {
670 // If you do `x OP y`, then the types of `x` and `y` must
671 // outlive the operation you are performing.
672 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
673 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
674 for &ty in &[lhs_ty, rhs_ty] {
675 self.type_must_outlive(infer::Operand(expr.span),
678 intravisit::walk_expr(self, expr);
681 hir::ExprUnary(op, ref lhs) if has_method_map => {
682 let implicitly_ref_args = !op.is_by_value();
685 self.constrain_call(expr, Some(&lhs),
686 None::<hir::Expr>.iter(), implicitly_ref_args);
688 intravisit::walk_expr(self, expr);
691 hir::ExprUnary(hir::UnDeref, ref base) => {
692 // For *a, the lifetime of a must enclose the deref
693 let method_call = MethodCall::expr(expr.id);
694 let base_ty = match self.tables.borrow().method_map.get(&method_call) {
696 self.constrain_call(expr, Some(&base),
697 None::<hir::Expr>.iter(), true);
698 // late-bound regions in overloaded method calls are instantiated
699 let fn_ret = self.tcx.no_late_bound_regions(&method.ty.fn_ret());
702 None => self.resolve_node_type(base.id)
704 if let ty::TyRef(r_ptr, _) = base_ty.sty {
705 self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
708 intravisit::walk_expr(self, expr);
711 hir::ExprIndex(ref vec_expr, _) => {
712 // For a[b], the lifetime of a must enclose the deref
713 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
714 self.constrain_index(expr, vec_type);
716 intravisit::walk_expr(self, expr);
719 hir::ExprCast(ref source, _) => {
720 // Determine if we are casting `source` to a trait
721 // instance. If so, we have to be sure that the type of
722 // the source obeys the trait's region bound.
723 self.constrain_cast(expr, &source);
724 intravisit::walk_expr(self, expr);
727 hir::ExprAddrOf(m, ref base) => {
728 self.link_addr_of(expr, m, &base);
730 // Require that when you write a `&expr` expression, the
731 // resulting pointer has a lifetime that encompasses the
732 // `&expr` expression itself. Note that we constraining
733 // the type of the node expr.id here *before applying
736 // FIXME(#6268) nested method calls requires that this rule change
737 let ty0 = self.resolve_node_type(expr.id);
738 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
739 intravisit::walk_expr(self, expr);
742 hir::ExprMatch(ref discr, ref arms, _) => {
743 self.link_match(&discr, &arms[..]);
745 intravisit::walk_expr(self, expr);
748 hir::ExprClosure(.., body_id, _) => {
749 self.check_expr_fn_block(expr, body_id);
752 hir::ExprLoop(ref body, _, _) => {
753 let repeating_scope = self.set_repeating_scope(body.id);
754 intravisit::walk_expr(self, expr);
755 self.set_repeating_scope(repeating_scope);
758 hir::ExprWhile(ref cond, ref body, _) => {
759 let repeating_scope = self.set_repeating_scope(cond.id);
760 self.visit_expr(&cond);
762 self.set_repeating_scope(body.id);
763 self.visit_block(&body);
765 self.set_repeating_scope(repeating_scope);
768 hir::ExprRet(Some(ref ret_expr)) => {
769 let call_site_scope = self.call_site_scope;
770 debug!("visit_expr ExprRet ret_expr.id {} call_site_scope: {:?}",
771 ret_expr.id, call_site_scope);
772 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
773 self.type_of_node_must_outlive(infer::CallReturn(ret_expr.span),
776 intravisit::walk_expr(self, expr);
780 intravisit::walk_expr(self, expr);
786 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
787 fn constrain_cast(&mut self,
788 cast_expr: &hir::Expr,
789 source_expr: &hir::Expr)
791 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
795 let source_ty = self.resolve_node_type(source_expr.id);
796 let target_ty = self.resolve_node_type(cast_expr.id);
798 self.walk_cast(cast_expr, source_ty, target_ty);
801 fn walk_cast(&mut self,
802 cast_expr: &hir::Expr,
805 debug!("walk_cast(from_ty={:?}, to_ty={:?})",
808 match (&from_ty.sty, &to_ty.sty) {
809 /*From:*/ (&ty::TyRef(from_r, ref from_mt),
810 /*To: */ &ty::TyRef(to_r, ref to_mt)) => {
811 // Target cannot outlive source, naturally.
812 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
813 self.walk_cast(cast_expr, from_mt.ty, to_mt.ty);
817 /*To: */ &ty::TyDynamic(.., r)) => {
818 // When T is existentially quantified as a trait
819 // `Foo+'to`, it must outlive the region bound `'to`.
820 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
823 /*From:*/ (&ty::TyAdt(from_def, _),
824 /*To: */ &ty::TyAdt(to_def, _)) if from_def.is_box() && to_def.is_box() => {
825 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
832 fn check_expr_fn_block(&mut self,
833 expr: &'gcx hir::Expr,
834 body_id: hir::BodyId) {
835 let repeating_scope = self.set_repeating_scope(body_id.node_id);
836 intravisit::walk_expr(self, expr);
837 self.set_repeating_scope(repeating_scope);
840 fn constrain_callee(&mut self,
841 callee_id: ast::NodeId,
842 _call_expr: &hir::Expr,
843 _callee_expr: &hir::Expr) {
844 let callee_ty = self.resolve_node_type(callee_id);
845 match callee_ty.sty {
846 ty::TyFnDef(..) | ty::TyFnPtr(_) => { }
848 // this should not happen, but it does if the program is
853 // "Calling non-function: {}",
859 fn constrain_call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
860 call_expr: &hir::Expr,
861 receiver: Option<&hir::Expr>,
863 implicitly_ref_args: bool) {
864 //! Invoked on every call site (i.e., normal calls, method calls,
865 //! and overloaded operators). Constrains the regions which appear
866 //! in the type of the function. Also constrains the regions that
867 //! appear in the arguments appropriately.
869 debug!("constrain_call(call_expr={:?}, \
871 implicitly_ref_args={})",
874 implicitly_ref_args);
876 // `callee_region` is the scope representing the time in which the
879 // FIXME(#6268) to support nested method calls, should be callee_id
880 let callee_scope = CodeExtent::Misc(call_expr.id);
881 let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
883 debug!("callee_region={:?}", callee_region);
885 for arg_expr in arg_exprs {
886 debug!("Argument: {:?}", arg_expr);
888 // ensure that any regions appearing in the argument type are
889 // valid for at least the lifetime of the function:
890 self.type_of_node_must_outlive(infer::CallArg(arg_expr.span),
891 arg_expr.id, callee_region);
893 // unfortunately, there are two means of taking implicit
894 // references, and we need to propagate constraints as a
895 // result. modes are going away and the "DerefArgs" code
896 // should be ported to use adjustments
897 if implicitly_ref_args {
898 self.link_by_ref(arg_expr, callee_scope);
902 // as loop above, but for receiver
903 if let Some(r) = receiver {
904 debug!("receiver: {:?}", r);
905 self.type_of_node_must_outlive(infer::CallRcvr(r.span),
906 r.id, callee_region);
907 if implicitly_ref_args {
908 self.link_by_ref(&r, callee_scope);
913 /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being
914 /// dereferenced, the lifetime of the pointer includes the deref expr.
915 fn constrain_autoderefs(&mut self,
916 deref_expr: &hir::Expr,
918 mut derefd_ty: Ty<'tcx>)
920 debug!("constrain_autoderefs(deref_expr={:?}, derefs={}, derefd_ty={:?})",
925 let r_deref_expr = self.tcx.node_scope_region(deref_expr.id);
927 let method_call = MethodCall::autoderef(deref_expr.id, i as u32);
928 debug!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call, derefs);
930 let method = self.tables.borrow().method_map.get(&method_call).map(|m| m.clone());
932 derefd_ty = match method {
934 debug!("constrain_autoderefs: #{} is overloaded, method={:?}",
937 let origin = infer::ParameterOrigin::OverloadedDeref;
938 self.substs_wf_in_scope(origin, method.substs, deref_expr.span, r_deref_expr);
940 // Treat overloaded autoderefs as if an AutoBorrow adjustment
941 // was applied on the base type, as that is always the case.
942 let fn_sig = method.ty.fn_sig();
943 let fn_sig = // late-bound regions should have been instantiated
944 self.tcx.no_late_bound_regions(&fn_sig).unwrap();
945 let self_ty = fn_sig.inputs()[0];
946 let (m, r) = match self_ty.sty {
947 ty::TyRef(r, ref m) => (m.mutbl, r),
951 "bad overloaded deref type {:?}",
956 debug!("constrain_autoderefs: receiver r={:?} m={:?}",
960 let mc = mc::MemCategorizationContext::new(self, &self.region_maps);
961 let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i));
962 debug!("constrain_autoderefs: self_cmt={:?}",
964 self.link_region(deref_expr.span, r,
965 ty::BorrowKind::from_mutbl(m), self_cmt);
968 // Specialized version of constrain_call.
969 self.type_must_outlive(infer::CallRcvr(deref_expr.span),
970 self_ty, r_deref_expr);
971 self.type_must_outlive(infer::CallReturn(deref_expr.span),
972 fn_sig.output(), r_deref_expr);
978 if let ty::TyRef(r_ptr, _) = derefd_ty.sty {
979 self.mk_subregion_due_to_dereference(deref_expr.span,
980 r_deref_expr, r_ptr);
983 match derefd_ty.builtin_deref(true, ty::NoPreference) {
984 Some(mt) => derefd_ty = mt.ty,
985 /* if this type can't be dereferenced, then there's already an error
986 in the session saying so. Just bail out for now */
992 pub fn mk_subregion_due_to_dereference(&mut self,
994 minimum_lifetime: ty::Region<'tcx>,
995 maximum_lifetime: ty::Region<'tcx>) {
996 self.sub_regions(infer::DerefPointer(deref_span),
997 minimum_lifetime, maximum_lifetime)
1000 fn check_safety_of_rvalue_destructor_if_necessary(&mut self,
1004 Categorization::Rvalue(region, _) => {
1006 ty::ReScope(rvalue_scope) => {
1007 let typ = self.resolve_type(cmt.ty);
1008 let _ = dropck::check_safety_of_destructor_if_necessary(
1009 self, typ, span, rvalue_scope);
1014 "unexpected rvalue region in rvalue \
1015 destructor safety checking: `{:?}`",
1024 /// Invoked on any index expression that occurs. Checks that if this is a slice
1025 /// being indexed, the lifetime of the pointer includes the deref expr.
1026 fn constrain_index(&mut self,
1027 index_expr: &hir::Expr,
1028 indexed_ty: Ty<'tcx>)
1030 debug!("constrain_index(index_expr=?, indexed_ty={}",
1031 self.ty_to_string(indexed_ty));
1033 let r_index_expr = ty::ReScope(CodeExtent::Misc(index_expr.id));
1034 if let ty::TyRef(r_ptr, mt) = indexed_ty.sty {
1036 ty::TySlice(_) | ty::TyStr => {
1037 self.sub_regions(infer::IndexSlice(index_expr.span),
1038 self.tcx.mk_region(r_index_expr), r_ptr);
1045 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1046 /// adjustments) are valid for at least `minimum_lifetime`
1047 fn type_of_node_must_outlive(&mut self,
1048 origin: infer::SubregionOrigin<'tcx>,
1050 minimum_lifetime: ty::Region<'tcx>)
1052 // Try to resolve the type. If we encounter an error, then typeck
1053 // is going to fail anyway, so just stop here and let typeck
1054 // report errors later on in the writeback phase.
1055 let ty0 = self.resolve_node_type(id);
1056 let ty = self.tables.borrow().adjustments.get(&id).map_or(ty0, |adj| adj.target);
1057 let ty = self.resolve_type(ty);
1058 debug!("constrain_regions_in_type_of_node(\
1059 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
1061 id, minimum_lifetime);
1062 self.type_must_outlive(origin, ty, minimum_lifetime);
1065 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1066 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1067 fn link_addr_of(&mut self, expr: &hir::Expr,
1068 mutability: hir::Mutability, base: &hir::Expr) {
1069 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
1072 let mc = mc::MemCategorizationContext::new(self, &self.region_maps);
1073 ignore_err!(mc.cat_expr(base))
1076 debug!("link_addr_of: cmt={:?}", cmt);
1078 self.link_region_from_node_type(expr.span, expr.id, mutability, cmt);
1081 /// Computes the guarantors for any ref bindings in a `let` and
1082 /// then ensures that the lifetime of the resulting pointer is
1083 /// linked to the lifetime of the initialization expression.
1084 fn link_local(&self, local: &hir::Local) {
1085 debug!("regionck::for_local()");
1086 let init_expr = match local.init {
1088 Some(ref expr) => &**expr,
1090 let mc = &mc::MemCategorizationContext::new(self, &self.region_maps);
1091 let discr_cmt = ignore_err!(mc.cat_expr(init_expr));
1092 self.link_pattern(mc, discr_cmt, &local.pat);
1095 /// Computes the guarantors for any ref bindings in a match and
1096 /// then ensures that the lifetime of the resulting pointer is
1097 /// linked to the lifetime of its guarantor (if any).
1098 fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) {
1099 debug!("regionck::for_match()");
1100 let mc = &mc::MemCategorizationContext::new(self, &self.region_maps);
1101 let discr_cmt = ignore_err!(mc.cat_expr(discr));
1102 debug!("discr_cmt={:?}", discr_cmt);
1104 for root_pat in &arm.pats {
1105 self.link_pattern(mc, discr_cmt.clone(), &root_pat);
1110 /// Computes the guarantors for any ref bindings in a match and
1111 /// then ensures that the lifetime of the resulting pointer is
1112 /// linked to the lifetime of its guarantor (if any).
1113 fn link_fn_args(&self, body_scope: CodeExtent, args: &[hir::Arg]) {
1114 debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1115 let mc = &mc::MemCategorizationContext::new(self, &self.region_maps);
1117 let arg_ty = self.node_ty(arg.id);
1118 let re_scope = self.tcx.mk_region(ty::ReScope(body_scope));
1119 let arg_cmt = mc.cat_rvalue(
1120 arg.id, arg.pat.span, re_scope, re_scope, arg_ty);
1121 debug!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1125 self.link_pattern(mc, arg_cmt, &arg.pat);
1129 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1130 /// in the discriminant, if needed.
1131 fn link_pattern<'t>(&self,
1132 mc: &mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
1133 discr_cmt: mc::cmt<'tcx>,
1134 root_pat: &hir::Pat) {
1135 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1138 let _ = mc.cat_pattern(discr_cmt, root_pat, |_, sub_cmt, sub_pat| {
1139 match sub_pat.node {
1141 PatKind::Binding(hir::BindByRef(mutbl), ..) => {
1142 self.link_region_from_node_type(sub_pat.span, sub_pat.id,
1150 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1152 fn link_autoref(&self,
1155 autoref: &adjustment::AutoBorrow<'tcx>)
1157 debug!("link_autoref(autoderefs={}, autoref={:?})", autoderefs, autoref);
1158 let mc = mc::MemCategorizationContext::new(self, &self.region_maps);
1159 let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs));
1160 debug!("expr_cmt={:?}", expr_cmt);
1163 adjustment::AutoBorrow::Ref(r, m) => {
1164 self.link_region(expr.span, r,
1165 ty::BorrowKind::from_mutbl(m), expr_cmt);
1168 adjustment::AutoBorrow::RawPtr(m) => {
1169 let r = self.tcx.node_scope_region(expr.id);
1170 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1175 /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and
1176 /// must outlive `callee_scope`.
1177 fn link_by_ref(&self,
1179 callee_scope: CodeExtent) {
1180 debug!("link_by_ref(expr={:?}, callee_scope={:?})",
1181 expr, callee_scope);
1182 let mc = mc::MemCategorizationContext::new(self, &self.region_maps);
1183 let expr_cmt = ignore_err!(mc.cat_expr(expr));
1184 let borrow_region = self.tcx.mk_region(ty::ReScope(callee_scope));
1185 self.link_region(expr.span, borrow_region, ty::ImmBorrow, expr_cmt);
1188 /// Like `link_region()`, except that the region is extracted from the type of `id`,
1189 /// which must be some reference (`&T`, `&str`, etc).
1190 fn link_region_from_node_type(&self,
1193 mutbl: hir::Mutability,
1194 cmt_borrowed: mc::cmt<'tcx>) {
1195 debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1196 id, mutbl, cmt_borrowed);
1198 let rptr_ty = self.resolve_node_type(id);
1199 if let ty::TyRef(r, _) = rptr_ty.sty {
1200 debug!("rptr_ty={}", rptr_ty);
1201 self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl),
1206 /// Informs the inference engine that `borrow_cmt` is being borrowed with
1207 /// kind `borrow_kind` and lifetime `borrow_region`.
1208 /// In order to ensure borrowck is satisfied, this may create constraints
1209 /// between regions, as explained in `link_reborrowed_region()`.
1210 fn link_region(&self,
1212 borrow_region: ty::Region<'tcx>,
1213 borrow_kind: ty::BorrowKind,
1214 borrow_cmt: mc::cmt<'tcx>) {
1215 let mut borrow_cmt = borrow_cmt;
1216 let mut borrow_kind = borrow_kind;
1218 let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1219 self.type_must_outlive(origin, borrow_cmt.ty, borrow_region);
1222 debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1226 match borrow_cmt.cat.clone() {
1227 Categorization::Deref(ref_cmt, _,
1228 mc::Implicit(ref_kind, ref_region)) |
1229 Categorization::Deref(ref_cmt, _,
1230 mc::BorrowedPtr(ref_kind, ref_region)) => {
1231 match self.link_reborrowed_region(span,
1232 borrow_region, borrow_kind,
1233 ref_cmt, ref_region, ref_kind,
1245 Categorization::Downcast(cmt_base, _) |
1246 Categorization::Deref(cmt_base, _, mc::Unique) |
1247 Categorization::Interior(cmt_base, _) => {
1248 // Borrowing interior or owned data requires the base
1249 // to be valid and borrowable in the same fashion.
1250 borrow_cmt = cmt_base;
1251 borrow_kind = borrow_kind;
1254 Categorization::Deref(.., mc::UnsafePtr(..)) |
1255 Categorization::StaticItem |
1256 Categorization::Upvar(..) |
1257 Categorization::Local(..) |
1258 Categorization::Rvalue(..) => {
1259 // These are all "base cases" with independent lifetimes
1260 // that are not subject to inference
1267 /// This is the most complicated case: the path being borrowed is
1268 /// itself the referent of a borrowed pointer. Let me give an
1269 /// example fragment of code to make clear(er) the situation:
1271 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1273 /// &'z *r // the reborrow has lifetime 'z
1275 /// Now, in this case, our primary job is to add the inference
1276 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1277 /// parameters in (roughly) terms of the example:
1279 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1280 /// borrow_region ^~ ref_region ^~
1281 /// borrow_kind ^~ ref_kind ^~
1284 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1286 /// Unfortunately, there are some complications beyond the simple
1287 /// scenario I just painted:
1289 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1290 /// case, we have two jobs. First, we are inferring whether this reference
1291 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1292 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1293 /// then `r` must be an `&mut` reference). Second, whenever we link
1294 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1295 /// case we adjust the cause to indicate that the reference being
1296 /// "reborrowed" is itself an upvar. This provides a nicer error message
1297 /// should something go wrong.
1299 /// 2. There may in fact be more levels of reborrowing. In the
1300 /// example, I said the borrow was like `&'z *r`, but it might
1301 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1302 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1303 /// and `'z <= 'b`. This is explained more below.
1305 /// The return value of this function indicates whether we need to
1306 /// recurse and process `ref_cmt` (see case 2 above).
1307 fn link_reborrowed_region(&self,
1309 borrow_region: ty::Region<'tcx>,
1310 borrow_kind: ty::BorrowKind,
1311 ref_cmt: mc::cmt<'tcx>,
1312 ref_region: ty::Region<'tcx>,
1313 mut ref_kind: ty::BorrowKind,
1315 -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1317 // Possible upvar ID we may need later to create an entry in the
1320 // Detect by-ref upvar `x`:
1321 let cause = match note {
1322 mc::NoteUpvarRef(ref upvar_id) => {
1323 let upvar_capture_map = &self.tables.borrow_mut().upvar_capture_map;
1324 match upvar_capture_map.get(upvar_id) {
1325 Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1326 // The mutability of the upvar may have been modified
1327 // by the above adjustment, so update our local variable.
1328 ref_kind = upvar_borrow.kind;
1330 infer::ReborrowUpvar(span, *upvar_id)
1333 span_bug!( span, "Illegal upvar id: {:?}", upvar_id);
1337 mc::NoteClosureEnv(ref upvar_id) => {
1338 // We don't have any mutability changes to propagate, but
1339 // we do want to note that an upvar reborrow caused this
1341 infer::ReborrowUpvar(span, *upvar_id)
1344 infer::Reborrow(span)
1348 debug!("link_reborrowed_region: {:?} <= {:?}",
1351 self.sub_regions(cause, borrow_region, ref_region);
1353 // If we end up needing to recurse and establish a region link
1354 // with `ref_cmt`, calculate what borrow kind we will end up
1355 // needing. This will be used below.
1357 // One interesting twist is that we can weaken the borrow kind
1358 // when we recurse: to reborrow an `&mut` referent as mutable,
1359 // borrowck requires a unique path to the `&mut` reference but not
1360 // necessarily a *mutable* path.
1361 let new_borrow_kind = match borrow_kind {
1364 ty::MutBorrow | ty::UniqueImmBorrow =>
1368 // Decide whether we need to recurse and link any regions within
1369 // the `ref_cmt`. This is concerned for the case where the value
1370 // being reborrowed is in fact a borrowed pointer found within
1371 // another borrowed pointer. For example:
1373 // let p: &'b &'a mut T = ...;
1377 // What makes this case particularly tricky is that, if the data
1378 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1379 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1380 // (otherwise the user might mutate through the `&mut T` reference
1381 // after `'b` expires and invalidate the borrow we are looking at
1384 // So let's re-examine our parameters in light of this more
1385 // complicated (possible) scenario:
1387 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1388 // borrow_region ^~ ref_region ^~
1389 // borrow_kind ^~ ref_kind ^~
1392 // (Note that since we have not examined `ref_cmt.cat`, we don't
1393 // know whether this scenario has occurred; but I wanted to show
1394 // how all the types get adjusted.)
1397 // The reference being reborrowed is a sharable ref of
1398 // type `&'a T`. In this case, it doesn't matter where we
1399 // *found* the `&T` pointer, the memory it references will
1400 // be valid and immutable for `'a`. So we can stop here.
1402 // (Note that the `borrow_kind` must also be ImmBorrow or
1403 // else the user is borrowed imm memory as mut memory,
1404 // which means they'll get an error downstream in borrowck
1409 ty::MutBorrow | ty::UniqueImmBorrow => {
1410 // The reference being reborrowed is either an `&mut T` or
1411 // `&uniq T`. This is the case where recursion is needed.
1412 return Some((ref_cmt, new_borrow_kind));
1417 /// Checks that the values provided for type/region arguments in a given
1418 /// expression are well-formed and in-scope.
1419 fn substs_wf_in_scope(&mut self,
1420 origin: infer::ParameterOrigin,
1421 substs: &Substs<'tcx>,
1423 expr_region: ty::Region<'tcx>) {
1424 debug!("substs_wf_in_scope(substs={:?}, \
1428 substs, expr_region, origin, expr_span);
1430 let origin = infer::ParameterInScope(origin, expr_span);
1432 for region in substs.regions() {
1433 self.sub_regions(origin.clone(), expr_region, region);
1436 for ty in substs.types() {
1437 let ty = self.resolve_type(ty);
1438 self.type_must_outlive(origin.clone(), ty, expr_region);
1442 /// Ensures that type is well-formed in `region`, which implies (among
1443 /// other things) that all borrowed data reachable via `ty` outlives
1445 pub fn type_must_outlive(&self,
1446 origin: infer::SubregionOrigin<'tcx>,
1448 region: ty::Region<'tcx>)
1450 let ty = self.resolve_type(ty);
1452 debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})",
1457 assert!(!ty.has_escaping_regions());
1459 let components = self.tcx.outlives_components(ty);
1460 self.components_must_outlive(origin, components, region);
1463 fn components_must_outlive(&self,
1464 origin: infer::SubregionOrigin<'tcx>,
1465 components: Vec<ty::outlives::Component<'tcx>>,
1466 region: ty::Region<'tcx>)
1468 for component in components {
1469 let origin = origin.clone();
1471 ty::outlives::Component::Region(region1) => {
1472 self.sub_regions(origin, region, region1);
1474 ty::outlives::Component::Param(param_ty) => {
1475 self.param_ty_must_outlive(origin, region, param_ty);
1477 ty::outlives::Component::Projection(projection_ty) => {
1478 self.projection_must_outlive(origin, region, projection_ty);
1480 ty::outlives::Component::EscapingProjection(subcomponents) => {
1481 self.components_must_outlive(origin, subcomponents, region);
1483 ty::outlives::Component::UnresolvedInferenceVariable(v) => {
1484 // ignore this, we presume it will yield an error
1485 // later, since if a type variable is not resolved by
1486 // this point it never will be
1487 self.tcx.sess.delay_span_bug(
1489 &format!("unresolved inference variable in outlives: {:?}", v));
1495 fn param_ty_must_outlive(&self,
1496 origin: infer::SubregionOrigin<'tcx>,
1497 region: ty::Region<'tcx>,
1498 param_ty: ty::ParamTy) {
1499 debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1500 region, param_ty, origin);
1502 let verify_bound = self.param_bound(param_ty);
1503 let generic = GenericKind::Param(param_ty);
1504 self.verify_generic_bound(origin, generic, region, verify_bound);
1507 fn projection_must_outlive(&self,
1508 origin: infer::SubregionOrigin<'tcx>,
1509 region: ty::Region<'tcx>,
1510 projection_ty: ty::ProjectionTy<'tcx>)
1512 debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1513 region, projection_ty, origin);
1515 // This case is thorny for inference. The fundamental problem is
1516 // that there are many cases where we have choice, and inference
1517 // doesn't like choice (the current region inference in
1518 // particular). :) First off, we have to choose between using the
1519 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1520 // OutlivesProjectionComponent rules, any one of which is
1521 // sufficient. If there are no inference variables involved, it's
1522 // not hard to pick the right rule, but if there are, we're in a
1523 // bit of a catch 22: if we picked which rule we were going to
1524 // use, we could add constraints to the region inference graph
1525 // that make it apply, but if we don't add those constraints, the
1526 // rule might not apply (but another rule might). For now, we err
1527 // on the side of adding too few edges into the graph.
1529 // Compute the bounds we can derive from the environment or trait
1530 // definition. We know that the projection outlives all the
1531 // regions in this list.
1532 let env_bounds = self.projection_declared_bounds(origin.span(), projection_ty);
1534 debug!("projection_must_outlive: env_bounds={:?}",
1537 // If we know that the projection outlives 'static, then we're
1539 if env_bounds.contains(&&ty::ReStatic) {
1540 debug!("projection_must_outlive: 'static as declared bound");
1544 // If declared bounds list is empty, the only applicable rule is
1545 // OutlivesProjectionComponent. If there are inference variables,
1546 // then, we can break down the outlives into more primitive
1547 // components without adding unnecessary edges.
1549 // If there are *no* inference variables, however, we COULD do
1550 // this, but we choose not to, because the error messages are less
1551 // good. For example, a requirement like `T::Item: 'r` would be
1552 // translated to a requirement that `T: 'r`; when this is reported
1553 // to the user, it will thus say "T: 'r must hold so that T::Item:
1554 // 'r holds". But that makes it sound like the only way to fix
1555 // the problem is to add `T: 'r`, which isn't true. So, if there are no
1556 // inference variables, we use a verify constraint instead of adding
1557 // edges, which winds up enforcing the same condition.
1558 let needs_infer = projection_ty.trait_ref.needs_infer();
1559 if env_bounds.is_empty() && needs_infer {
1560 debug!("projection_must_outlive: no declared bounds");
1562 for component_ty in projection_ty.trait_ref.substs.types() {
1563 self.type_must_outlive(origin.clone(), component_ty, region);
1566 for r in projection_ty.trait_ref.substs.regions() {
1567 self.sub_regions(origin.clone(), region, r);
1573 // If we find that there is a unique declared bound `'b`, and this bound
1574 // appears in the trait reference, then the best action is to require that `'b:'r`,
1575 // so do that. This is best no matter what rule we use:
1577 // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1578 // the requirement that `'b:'r`
1579 // - OutlivesProjectionComponent: this would require `'b:'r` in addition to
1581 if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) {
1582 let unique_bound = env_bounds[0];
1583 debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound);
1584 if projection_ty.trait_ref.substs.regions().any(|r| env_bounds.contains(&r)) {
1585 debug!("projection_must_outlive: unique declared bound appears in trait ref");
1586 self.sub_regions(origin.clone(), region, unique_bound);
1591 // Fallback to verifying after the fact that there exists a
1592 // declared bound, or that all the components appearing in the
1593 // projection outlive; in some cases, this may add insufficient
1594 // edges into the inference graph, leading to inference failures
1595 // even though a satisfactory solution exists.
1596 let verify_bound = self.projection_bound(origin.span(), env_bounds, projection_ty);
1597 let generic = GenericKind::Projection(projection_ty);
1598 self.verify_generic_bound(origin, generic.clone(), region, verify_bound);
1601 fn type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1606 ty::TyProjection(data) => {
1607 let declared_bounds = self.projection_declared_bounds(span, data);
1608 self.projection_bound(span, declared_bounds, data)
1611 self.recursive_type_bound(span, ty)
1616 fn param_bound(&self, param_ty: ty::ParamTy) -> VerifyBound<'tcx> {
1617 debug!("param_bound(param_ty={:?})",
1620 let mut param_bounds = self.declared_generic_bounds_from_env(GenericKind::Param(param_ty));
1622 // Add in the default bound of fn body that applies to all in
1623 // scope type parameters:
1624 param_bounds.extend(self.implicit_region_bound);
1626 VerifyBound::AnyRegion(param_bounds)
1629 fn projection_declared_bounds(&self,
1631 projection_ty: ty::ProjectionTy<'tcx>)
1632 -> Vec<ty::Region<'tcx>>
1634 // First assemble bounds from where clauses and traits.
1636 let mut declared_bounds =
1637 self.declared_generic_bounds_from_env(GenericKind::Projection(projection_ty));
1639 declared_bounds.extend_from_slice(
1640 &self.declared_projection_bounds_from_trait(span, projection_ty));
1645 fn projection_bound(&self,
1647 declared_bounds: Vec<ty::Region<'tcx>>,
1648 projection_ty: ty::ProjectionTy<'tcx>)
1649 -> VerifyBound<'tcx> {
1650 debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1651 declared_bounds, projection_ty);
1653 // see the extensive comment in projection_must_outlive
1655 let ty = self.tcx.mk_projection(projection_ty.trait_ref, projection_ty.item_name);
1656 let recursive_bound = self.recursive_type_bound(span, ty);
1658 VerifyBound::AnyRegion(declared_bounds).or(recursive_bound)
1661 fn recursive_type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1662 let mut bounds = vec![];
1664 for subty in ty.walk_shallow() {
1665 bounds.push(self.type_bound(span, subty));
1668 let mut regions = ty.regions();
1669 regions.retain(|r| !r.is_late_bound()); // ignore late-bound regions
1670 bounds.push(VerifyBound::AllRegions(regions));
1672 // remove bounds that must hold, since they are not interesting
1673 bounds.retain(|b| !b.must_hold());
1675 if bounds.len() == 1 {
1676 bounds.pop().unwrap()
1678 VerifyBound::AllBounds(bounds)
1682 fn declared_generic_bounds_from_env(&self, generic: GenericKind<'tcx>)
1683 -> Vec<ty::Region<'tcx>>
1685 let param_env = &self.parameter_environment;
1687 // To start, collect bounds from user:
1688 let mut param_bounds = self.tcx.required_region_bounds(generic.to_ty(self.tcx),
1689 param_env.caller_bounds.to_vec());
1691 // Next, collect regions we scraped from the well-formedness
1692 // constraints in the fn signature. To do that, we walk the list
1693 // of known relations from the fn ctxt.
1695 // This is crucial because otherwise code like this fails:
1697 // fn foo<'a, A>(x: &'a A) { x.bar() }
1699 // The problem is that the type of `x` is `&'a A`. To be
1700 // well-formed, then, A must be lower-generic by `'a`, but we
1701 // don't know that this holds from first principles.
1702 for &(r, p) in &self.region_bound_pairs {
1703 debug!("generic={:?} p={:?}",
1707 param_bounds.push(r);
1714 fn declared_projection_bounds_from_trait(&self,
1716 projection_ty: ty::ProjectionTy<'tcx>)
1717 -> Vec<ty::Region<'tcx>>
1719 debug!("projection_bounds(projection_ty={:?})",
1722 let ty = self.tcx.mk_projection(projection_ty.trait_ref.clone(),
1723 projection_ty.item_name);
1725 // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1726 // in looking for a trait definition like:
1729 // trait SomeTrait<'a> {
1730 // type SomeType : 'a;
1734 // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1735 let trait_predicates = self.tcx.predicates_of(projection_ty.trait_ref.def_id);
1736 assert_eq!(trait_predicates.parent, None);
1737 let predicates = trait_predicates.predicates.as_slice().to_vec();
1738 traits::elaborate_predicates(self.tcx, predicates)
1739 .filter_map(|predicate| {
1740 // we're only interesting in `T : 'a` style predicates:
1741 let outlives = match predicate {
1742 ty::Predicate::TypeOutlives(data) => data,
1743 _ => { return None; }
1746 debug!("projection_bounds: outlives={:?} (1)",
1749 // apply the substitutions (and normalize any projected types)
1750 let outlives = self.instantiate_type_scheme(span,
1751 projection_ty.trait_ref.substs,
1754 debug!("projection_bounds: outlives={:?} (2)",
1757 let region_result = self.commit_if_ok(|_| {
1759 self.replace_late_bound_regions_with_fresh_var(
1761 infer::AssocTypeProjection(projection_ty.item_name),
1764 debug!("projection_bounds: outlives={:?} (3)",
1767 // check whether this predicate applies to our current projection
1768 let cause = self.fcx.misc(span);
1769 match self.eq_types(false, &cause, ty, outlives.0) {
1771 self.register_infer_ok_obligations(ok);
1774 Err(_) => { Err(()) }
1778 debug!("projection_bounds: region_result={:?}",