1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The region check is a final pass that runs over the AST after we have
12 //! inferred the type constraints but before we have actually finalized
13 //! the types. Its purpose is to embed a variety of region constraints.
14 //! Inserting these constraints as a separate pass is good because (1) it
15 //! localizes the code that has to do with region inference and (2) often
16 //! we cannot know what constraints are needed until the basic types have
19 //! ### Interaction with the borrow checker
21 //! In general, the job of the borrowck module (which runs later) is to
22 //! check that all soundness criteria are met, given a particular set of
23 //! regions. The job of *this* module is to anticipate the needs of the
24 //! borrow checker and infer regions that will satisfy its requirements.
25 //! It is generally true that the inference doesn't need to be sound,
26 //! meaning that if there is a bug and we inferred bad regions, the borrow
27 //! checker should catch it. This is not entirely true though; for
28 //! example, the borrow checker doesn't check subtyping, and it doesn't
29 //! check that region pointers are always live when they are used. It
30 //! might be worthwhile to fix this so that borrowck serves as a kind of
31 //! verification step -- that would add confidence in the overall
32 //! correctness of the compiler, at the cost of duplicating some type
33 //! checks and effort.
35 //! ### Inferring the duration of borrows, automatic and otherwise
37 //! Whenever we introduce a borrowed pointer, for example as the result of
38 //! a borrow expression `let x = &data`, the lifetime of the pointer `x`
39 //! is always specified as a region inference variable. `regionck` has the
40 //! job of adding constraints such that this inference variable is as
41 //! narrow as possible while still accommodating all uses (that is, every
42 //! dereference of the resulting pointer must be within the lifetime).
46 //! Generally speaking, `regionck` does NOT try to ensure that the data
47 //! `data` will outlive the pointer `x`. That is the job of borrowck. The
48 //! one exception is when "re-borrowing" the contents of another borrowed
49 //! pointer. For example, imagine you have a borrowed pointer `b` with
50 //! lifetime L1 and you have an expression `&*b`. The result of this
51 //! expression will be another borrowed pointer with lifetime L2 (which is
52 //! an inference variable). The borrow checker is going to enforce the
53 //! constraint that L2 < L1, because otherwise you are re-borrowing data
54 //! for a lifetime larger than the original loan. However, without the
55 //! routines in this module, the region inferencer would not know of this
56 //! dependency and thus it might infer the lifetime of L2 to be greater
57 //! than L1 (issue #3148).
59 //! There are a number of troublesome scenarios in the tests
60 //! `region-dependent-*.rs`, but here is one example:
62 //! struct Foo { i: int }
63 //! struct Bar { foo: Foo }
64 //! fn get_i(x: &'a Bar) -> &'a int {
65 //! let foo = &x.foo; // Lifetime L1
66 //! &foo.i // Lifetime L2
69 //! Note that this comes up either with `&` expressions, `ref`
70 //! bindings, and `autorefs`, which are the three ways to introduce
73 //! The key point here is that when you are borrowing a value that
74 //! is "guaranteed" by a borrowed pointer, you must link the
75 //! lifetime of that borrowed pointer (L1, here) to the lifetime of
76 //! the borrow itself (L2). What do I mean by "guaranteed" by a
77 //! borrowed pointer? I mean any data that is reached by first
78 //! dereferencing a borrowed pointer and then either traversing
79 //! interior offsets or boxes. We say that the guarantor
80 //! of such data is the region of the borrowed pointer that was
81 //! traversed. This is essentially the same as the ownership
82 //! relation, except that a borrowed pointer never owns its
88 use middle::free_region::FreeRegionMap;
89 use middle::implicator::{self, Implication};
90 use middle::mem_categorization as mc;
91 use middle::mem_categorization::Categorization;
92 use middle::region::CodeExtent;
93 use middle::subst::Substs;
95 use middle::ty::{self, RegionEscape, ReScope, Ty, MethodCall, HasTypeFlags};
96 use middle::infer::{self, GenericKind, InferCtxt, SubregionOrigin, TypeOrigin, VerifyBound};
98 use middle::ty::adjustment;
99 use middle::ty::wf::ImpliedBound;
104 use syntax::codemap::Span;
105 use rustc_front::intravisit::{self, 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);
287 let fn_sig_map = &self.infcx().tables.borrow().liberated_fn_sigs;
288 match fn_sig_map.get(&id) {
289 Some(f) => f.clone(),
292 &format!("No fn-sig entry for id={}", id));
297 let old_region_bounds_pairs_len = self.region_bound_pairs.len();
299 // Collect the types from which we create inferred bounds.
300 // For the return type, if diverging, substitute `bool` just
301 // because it will have no effect.
303 // FIXME(#25759) return types should not be implied bounds
304 let fn_sig_tys: Vec<_> =
307 .chain(Some(fn_sig.output.unwrap_or(self.tcx().types.bool)))
310 let old_body_id = self.set_body_id(body.id);
311 self.relate_free_regions(&fn_sig_tys[..], body.id, span);
313 self.tcx().region_maps.node_extent(body.id),
314 &fn_decl.inputs[..]);
315 self.visit_block(body);
316 self.visit_region_obligations(body.id);
318 self.region_bound_pairs.truncate(old_region_bounds_pairs_len);
320 self.set_body_id(old_body_id);
323 fn visit_region_obligations(&mut self, node_id: ast::NodeId)
325 debug!("visit_region_obligations: node_id={}", node_id);
327 // region checking can introduce new pending obligations
328 // which, when processed, might generate new region
329 // obligations. So make sure we process those.
330 self.fcx.select_all_obligations_or_error();
332 // Make a copy of the region obligations vec because we'll need
333 // to be able to borrow the fulfillment-cx below when projecting.
334 let region_obligations =
340 .region_obligations(node_id)
343 for r_o in ®ion_obligations {
344 debug!("visit_region_obligations: r_o={:?} cause={:?}",
346 let sup_type = self.resolve_type(r_o.sup_type);
347 let origin = self.code_to_origin(r_o.cause.span, sup_type, &r_o.cause.code);
349 if r_o.sub_region != ty::ReEmpty {
350 type_must_outlive(self, origin, sup_type, r_o.sub_region);
352 self.visit_old_school_wf(node_id, sup_type, origin);
356 // Processing the region obligations should not cause the list to grow further:
357 assert_eq!(region_obligations.len(),
358 self.fcx.inh.infcx.fulfillment_cx.borrow().region_obligations(node_id).len());
361 fn visit_old_school_wf(&mut self,
362 body_id: ast::NodeId,
364 origin: infer::SubregionOrigin<'tcx>) {
365 // As a weird kind of hack, we use a region of empty as a signal
366 // to mean "old-school WF rules". The only reason the old-school
367 // WF rules are not encoded using WF is that this leads to errors,
368 // and we want to phase those in gradually.
370 // FIXME(#27579) remove this weird special case once we phase in new WF rules completely
371 let implications = implicator::implications(self.infcx(),
376 let origin_for_ty = |ty: Option<Ty<'tcx>>| match ty {
377 None => origin.clone(),
378 Some(ty) => infer::ReferenceOutlivesReferent(ty, origin.span()),
380 for implication in implications {
382 Implication::RegionSubRegion(ty, r1, r2) => {
383 self.fcx.mk_subr(origin_for_ty(ty), r1, r2);
385 Implication::RegionSubGeneric(ty, r1, GenericKind::Param(param_ty)) => {
386 param_ty_must_outlive(self, origin_for_ty(ty), r1, param_ty);
388 Implication::RegionSubGeneric(ty, r1, GenericKind::Projection(proj_ty)) => {
389 projection_must_outlive(self, origin_for_ty(ty), r1, proj_ty);
391 Implication::Predicate(def_id, predicate) => {
392 let cause = traits::ObligationCause::new(origin.span(),
394 traits::ItemObligation(def_id));
395 let obligation = traits::Obligation::new(cause, predicate);
396 self.fcx.register_predicate(obligation);
402 fn code_to_origin(&self,
405 code: &traits::ObligationCauseCode<'tcx>)
406 -> SubregionOrigin<'tcx> {
408 traits::ObligationCauseCode::RFC1214(ref code) =>
409 infer::RFC1214Subregion(Rc::new(self.code_to_origin(span, sup_type, code))),
410 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
411 infer::ReferenceOutlivesReferent(ref_type, span),
413 infer::RelateParamBound(span, sup_type),
417 /// This method populates the region map's `free_region_map`. It walks over the transformed
418 /// argument and return types for each function just before we check the body of that function,
419 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
420 /// [usize]`. We do not allow references to outlive the things they point at, so we can assume
421 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
422 /// the caller side, the caller is responsible for checking that the type of every expression
423 /// (including the actual values for the arguments, as well as the return type of the fn call)
426 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
427 fn relate_free_regions(&mut self,
428 fn_sig_tys: &[Ty<'tcx>],
429 body_id: ast::NodeId,
431 debug!("relate_free_regions >>");
433 for &ty in fn_sig_tys {
434 let ty = self.resolve_type(ty);
435 debug!("relate_free_regions(t={:?})", ty);
436 let implied_bounds = ty::wf::implied_bounds(self.fcx.infcx(), body_id, ty, span);
438 // Record any relations between free regions that we observe into the free-region-map.
439 self.free_region_map.relate_free_regions_from_implied_bounds(&implied_bounds);
441 // But also record other relationships, such as `T:'x`,
442 // that don't go into the free-region-map but which we use
444 for implication in implied_bounds {
445 debug!("implication: {:?}", implication);
447 ImpliedBound::RegionSubRegion(ty::ReFree(free_a),
448 ty::ReVar(vid_b)) => {
449 self.fcx.inh.infcx.add_given(free_a, vid_b);
451 ImpliedBound::RegionSubParam(r_a, param_b) => {
452 self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
454 ImpliedBound::RegionSubProjection(r_a, projection_b) => {
455 self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
457 ImpliedBound::RegionSubRegion(..) => {
458 // In principle, we could record (and take
459 // advantage of) every relationship here, but
460 // we are also free not to -- it simply means
461 // strictly less that we can successfully type
462 // check. (It may also be that we should
463 // revise our inference system to be more
464 // general and to make use of *every*
465 // relationship that arises here, but
466 // presently we do not.)
472 debug!("<< relate_free_regions");
475 fn resolve_regions_and_report_errors(&self) {
476 let subject_node_id = match self.subject {
478 SubjectNode::None => {
479 self.tcx().sess.bug("cannot resolve_regions_and_report_errors \
480 without subject node");
484 self.fcx.infcx().resolve_regions_and_report_errors(&self.free_region_map,
489 impl<'a, 'tcx, 'v> Visitor<'v> for Rcx<'a, 'tcx> {
490 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
491 // However, right now we run into an issue whereby some free
492 // regions are not properly related if they appear within the
493 // types of arguments that must be inferred. This could be
494 // addressed by deferring the construction of the region
495 // hierarchy, and in particular the relationships between free
496 // regions, until regionck, as described in #3238.
498 fn visit_fn(&mut self, _fk: intravisit::FnKind<'v>, fd: &'v hir::FnDecl,
499 b: &'v hir::Block, span: Span, id: ast::NodeId) {
500 self.visit_fn_body(id, fd, b, span)
503 fn visit_expr(&mut self, ex: &hir::Expr) { visit_expr(self, ex); }
505 //visit_pat: visit_pat, // (..) see above
507 fn visit_arm(&mut self, a: &hir::Arm) { visit_arm(self, a); }
509 fn visit_local(&mut self, l: &hir::Local) { visit_local(self, l); }
511 fn visit_block(&mut self, b: &hir::Block) { visit_block(self, b); }
514 fn visit_block(rcx: &mut Rcx, b: &hir::Block) {
515 intravisit::walk_block(rcx, b);
518 fn visit_arm(rcx: &mut Rcx, arm: &hir::Arm) {
521 constrain_bindings_in_pat(&**p, rcx);
524 intravisit::walk_arm(rcx, arm);
527 fn visit_local(rcx: &mut Rcx, l: &hir::Local) {
529 constrain_bindings_in_pat(&*l.pat, rcx);
531 intravisit::walk_local(rcx, l);
534 fn constrain_bindings_in_pat(pat: &hir::Pat, rcx: &mut Rcx) {
535 let tcx = rcx.fcx.tcx();
536 debug!("regionck::visit_pat(pat={:?})", pat);
537 pat_util::pat_bindings(&tcx.def_map, pat, |_, id, span, _| {
538 // If we have a variable that contains region'd data, that
539 // data will be accessible from anywhere that the variable is
540 // accessed. We must be wary of loops like this:
542 // // from src/test/compile-fail/borrowck-lend-flow.rs
543 // let mut v = box 3, w = box 4;
544 // let mut x = &mut w;
547 // borrow(v); //~ ERROR cannot borrow
548 // x = &mut v; // (1)
551 // Typically, we try to determine the region of a borrow from
552 // those points where it is dereferenced. In this case, one
553 // might imagine that the lifetime of `x` need only be the
554 // body of the loop. But of course this is incorrect because
555 // the pointer that is created at point (1) is consumed at
556 // point (2), meaning that it must be live across the loop
557 // iteration. The easiest way to guarantee this is to require
558 // that the lifetime of any regions that appear in a
559 // variable's type enclose at least the variable's scope.
561 let var_scope = tcx.region_maps.var_scope(id);
563 let origin = infer::BindingTypeIsNotValidAtDecl(span);
564 type_of_node_must_outlive(rcx, origin, id, ty::ReScope(var_scope));
566 let typ = rcx.resolve_node_type(id);
567 dropck::check_safety_of_destructor_if_necessary(rcx, typ, span, var_scope);
571 fn visit_expr(rcx: &mut Rcx, expr: &hir::Expr) {
572 debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
573 expr, rcx.repeating_scope);
575 // No matter what, the type of each expression must outlive the
576 // scope of that expression. This also guarantees basic WF.
577 let expr_ty = rcx.resolve_node_type(expr.id);
578 // the region corresponding to this expression
579 let expr_region = ty::ReScope(rcx.tcx().region_maps.node_extent(expr.id));
580 type_must_outlive(rcx, infer::ExprTypeIsNotInScope(expr_ty, expr.span),
581 expr_ty, expr_region);
583 let method_call = MethodCall::expr(expr.id);
584 let opt_method_callee = rcx.fcx.inh.tables.borrow().method_map.get(&method_call).cloned();
585 let has_method_map = opt_method_callee.is_some();
587 // If we are calling a method (either explicitly or via an
588 // overloaded operator), check that all of the types provided as
589 // arguments for its type parameters are well-formed, and all the regions
590 // provided as arguments outlive the call.
591 if let Some(callee) = opt_method_callee {
592 let origin = match expr.node {
593 hir::ExprMethodCall(..) =>
594 infer::ParameterOrigin::MethodCall,
595 hir::ExprUnary(op, _) if op == hir::UnDeref =>
596 infer::ParameterOrigin::OverloadedDeref,
598 infer::ParameterOrigin::OverloadedOperator
601 substs_wf_in_scope(rcx, origin, &callee.substs, expr.span, expr_region);
602 type_must_outlive(rcx, infer::ExprTypeIsNotInScope(callee.ty, expr.span),
603 callee.ty, expr_region);
606 // Check any autoderefs or autorefs that appear.
607 let adjustment = rcx.fcx.inh.tables.borrow().adjustments.get(&expr.id).map(|a| a.clone());
608 if let Some(adjustment) = adjustment {
609 debug!("adjustment={:?}", adjustment);
611 adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
612 autoderefs, ref autoref, ..
614 let expr_ty = rcx.resolve_node_type(expr.id);
615 constrain_autoderefs(rcx, expr, autoderefs, expr_ty);
616 if let Some(ref autoref) = *autoref {
617 link_autoref(rcx, expr, autoderefs, autoref);
619 // Require that the resulting region encompasses
622 // FIXME(#6268) remove to support nested method calls
623 type_of_node_must_outlive(
624 rcx, infer::AutoBorrow(expr.span),
625 expr.id, expr_region);
629 adjustment::AutoObject(_, ref bounds, _, _) => {
630 // Determine if we are casting `expr` to a trait
631 // instance. If so, we have to be sure that the type
632 // of the source obeys the new region bound.
633 let source_ty = rcx.resolve_node_type(expr.id);
634 type_must_outlive(rcx, infer::RelateObjectBound(expr.span),
635 source_ty, bounds.region_bound);
641 // If necessary, constrain destructors in the unadjusted form of this
644 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
645 mc.cat_expr_unadjusted(expr)
649 check_safety_of_rvalue_destructor_if_necessary(rcx,
654 let tcx = rcx.fcx.tcx();
655 tcx.sess.delay_span_bug(expr.span, "cat_expr_unadjusted Errd");
660 // If necessary, constrain destructors in this expression. This will be
661 // the adjusted form if there is an adjustment.
663 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
668 check_safety_of_rvalue_destructor_if_necessary(rcx, head_cmt, expr.span);
671 let tcx = rcx.fcx.tcx();
672 tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
676 debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
677 expr, rcx.repeating_scope);
679 hir::ExprPath(..) => {
680 rcx.fcx.opt_node_ty_substs(expr.id, |item_substs| {
681 let origin = infer::ParameterOrigin::Path;
682 substs_wf_in_scope(rcx, origin, &item_substs.substs, expr.span, expr_region);
686 hir::ExprCall(ref callee, ref args) => {
688 constrain_call(rcx, expr, Some(&**callee),
689 args.iter().map(|e| &**e), false);
691 constrain_callee(rcx, callee.id, expr, &**callee);
692 constrain_call(rcx, expr, None,
693 args.iter().map(|e| &**e), false);
696 intravisit::walk_expr(rcx, expr);
699 hir::ExprMethodCall(_, _, ref args) => {
700 constrain_call(rcx, expr, Some(&*args[0]),
701 args[1..].iter().map(|e| &**e), false);
703 intravisit::walk_expr(rcx, expr);
706 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
708 constrain_call(rcx, expr, Some(&**lhs),
709 Some(&**rhs).into_iter(), false);
712 intravisit::walk_expr(rcx, expr);
715 hir::ExprIndex(ref lhs, ref rhs) if has_method_map => {
716 constrain_call(rcx, expr, Some(&**lhs),
717 Some(&**rhs).into_iter(), true);
719 intravisit::walk_expr(rcx, expr);
722 hir::ExprBinary(op, ref lhs, ref rhs) if has_method_map => {
723 let implicitly_ref_args = !hir_util::is_by_value_binop(op.node);
725 // As `expr_method_call`, but the call is via an
726 // overloaded op. Note that we (sadly) currently use an
727 // implicit "by ref" sort of passing style here. This
728 // should be converted to an adjustment!
729 constrain_call(rcx, expr, Some(&**lhs),
730 Some(&**rhs).into_iter(), implicitly_ref_args);
732 intravisit::walk_expr(rcx, expr);
735 hir::ExprBinary(_, ref lhs, ref rhs) => {
736 // If you do `x OP y`, then the types of `x` and `y` must
737 // outlive the operation you are performing.
738 let lhs_ty = rcx.resolve_expr_type_adjusted(&**lhs);
739 let rhs_ty = rcx.resolve_expr_type_adjusted(&**rhs);
740 for &ty in &[lhs_ty, rhs_ty] {
741 type_must_outlive(rcx,
742 infer::Operand(expr.span),
746 intravisit::walk_expr(rcx, expr);
749 hir::ExprUnary(op, ref lhs) if has_method_map => {
750 let implicitly_ref_args = !hir_util::is_by_value_unop(op);
753 constrain_call(rcx, expr, Some(&**lhs),
754 None::<hir::Expr>.iter(), implicitly_ref_args);
756 intravisit::walk_expr(rcx, expr);
759 hir::ExprUnary(hir::UnDeref, ref base) => {
760 // For *a, the lifetime of a must enclose the deref
761 let method_call = MethodCall::expr(expr.id);
762 let base_ty = match rcx.fcx.inh.tables.borrow().method_map.get(&method_call) {
764 constrain_call(rcx, expr, Some(&**base),
765 None::<hir::Expr>.iter(), true);
766 let fn_ret = // late-bound regions in overloaded method calls are instantiated
767 rcx.tcx().no_late_bound_regions(&method.ty.fn_ret()).unwrap();
770 None => rcx.resolve_node_type(base.id)
772 if let ty::TyRef(r_ptr, _) = base_ty.sty {
773 mk_subregion_due_to_dereference(
774 rcx, expr.span, expr_region, *r_ptr);
777 intravisit::walk_expr(rcx, expr);
780 hir::ExprIndex(ref vec_expr, _) => {
781 // For a[b], the lifetime of a must enclose the deref
782 let vec_type = rcx.resolve_expr_type_adjusted(&**vec_expr);
783 constrain_index(rcx, expr, vec_type);
785 intravisit::walk_expr(rcx, expr);
788 hir::ExprCast(ref source, _) => {
789 // Determine if we are casting `source` to a trait
790 // instance. If so, we have to be sure that the type of
791 // the source obeys the trait's region bound.
792 constrain_cast(rcx, expr, &**source);
793 intravisit::walk_expr(rcx, expr);
796 hir::ExprAddrOf(m, ref base) => {
797 link_addr_of(rcx, expr, m, &**base);
799 // Require that when you write a `&expr` expression, the
800 // resulting pointer has a lifetime that encompasses the
801 // `&expr` expression itself. Note that we constraining
802 // the type of the node expr.id here *before applying
805 // FIXME(#6268) nested method calls requires that this rule change
806 let ty0 = rcx.resolve_node_type(expr.id);
807 type_must_outlive(rcx, infer::AddrOf(expr.span), ty0, expr_region);
808 intravisit::walk_expr(rcx, expr);
811 hir::ExprMatch(ref discr, ref arms, _) => {
812 link_match(rcx, &**discr, &arms[..]);
814 intravisit::walk_expr(rcx, expr);
817 hir::ExprClosure(_, _, ref body) => {
818 check_expr_fn_block(rcx, expr, &**body);
821 hir::ExprLoop(ref body, _) => {
822 let repeating_scope = rcx.set_repeating_scope(body.id);
823 intravisit::walk_expr(rcx, expr);
824 rcx.set_repeating_scope(repeating_scope);
827 hir::ExprWhile(ref cond, ref body, _) => {
828 let repeating_scope = rcx.set_repeating_scope(cond.id);
829 rcx.visit_expr(&**cond);
831 rcx.set_repeating_scope(body.id);
832 rcx.visit_block(&**body);
834 rcx.set_repeating_scope(repeating_scope);
838 intravisit::walk_expr(rcx, expr);
843 fn constrain_cast(rcx: &mut Rcx,
844 cast_expr: &hir::Expr,
845 source_expr: &hir::Expr)
847 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
851 let source_ty = rcx.resolve_node_type(source_expr.id);
852 let target_ty = rcx.resolve_node_type(cast_expr.id);
854 walk_cast(rcx, cast_expr, source_ty, target_ty);
856 fn walk_cast<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
857 cast_expr: &hir::Expr,
860 debug!("walk_cast(from_ty={:?}, to_ty={:?})",
863 match (&from_ty.sty, &to_ty.sty) {
864 /*From:*/ (&ty::TyRef(from_r, ref from_mt),
865 /*To: */ &ty::TyRef(to_r, ref to_mt)) => {
866 // Target cannot outlive source, naturally.
867 rcx.fcx.mk_subr(infer::Reborrow(cast_expr.span), *to_r, *from_r);
868 walk_cast(rcx, cast_expr, from_mt.ty, to_mt.ty);
872 /*To: */ &ty::TyTrait(box ty::TraitTy { ref bounds, .. })) => {
873 // When T is existentially quantified as a trait
874 // `Foo+'to`, it must outlive the region bound `'to`.
875 type_must_outlive(rcx, infer::RelateObjectBound(cast_expr.span),
876 from_ty, bounds.region_bound);
879 /*From:*/ (&ty::TyBox(from_referent_ty),
880 /*To: */ &ty::TyBox(to_referent_ty)) => {
881 walk_cast(rcx, cast_expr, from_referent_ty, to_referent_ty);
889 fn check_expr_fn_block(rcx: &mut Rcx,
892 let repeating_scope = rcx.set_repeating_scope(body.id);
893 intravisit::walk_expr(rcx, expr);
894 rcx.set_repeating_scope(repeating_scope);
897 fn constrain_callee(rcx: &mut Rcx,
898 callee_id: ast::NodeId,
899 _call_expr: &hir::Expr,
900 _callee_expr: &hir::Expr) {
901 let callee_ty = rcx.resolve_node_type(callee_id);
902 match callee_ty.sty {
903 ty::TyBareFn(..) => { }
905 // this should not happen, but it does if the program is
908 // tcx.sess.span_bug(
910 // format!("Calling non-function: {}", callee_ty));
915 fn constrain_call<'a, I: Iterator<Item=&'a hir::Expr>>(rcx: &mut Rcx,
916 call_expr: &hir::Expr,
917 receiver: Option<&hir::Expr>,
919 implicitly_ref_args: bool) {
920 //! Invoked on every call site (i.e., normal calls, method calls,
921 //! and overloaded operators). Constrains the regions which appear
922 //! in the type of the function. Also constrains the regions that
923 //! appear in the arguments appropriately.
925 debug!("constrain_call(call_expr={:?}, \
927 implicitly_ref_args={})",
930 implicitly_ref_args);
932 // `callee_region` is the scope representing the time in which the
935 // FIXME(#6268) to support nested method calls, should be callee_id
936 let callee_scope = rcx.tcx().region_maps.node_extent(call_expr.id);
937 let callee_region = ty::ReScope(callee_scope);
939 debug!("callee_region={:?}", callee_region);
941 for arg_expr in arg_exprs {
942 debug!("Argument: {:?}", arg_expr);
944 // ensure that any regions appearing in the argument type are
945 // valid for at least the lifetime of the function:
946 type_of_node_must_outlive(
947 rcx, infer::CallArg(arg_expr.span),
948 arg_expr.id, callee_region);
950 // unfortunately, there are two means of taking implicit
951 // references, and we need to propagate constraints as a
952 // result. modes are going away and the "DerefArgs" code
953 // should be ported to use adjustments
954 if implicitly_ref_args {
955 link_by_ref(rcx, arg_expr, callee_scope);
959 // as loop above, but for receiver
960 if let Some(r) = receiver {
961 debug!("receiver: {:?}", r);
962 type_of_node_must_outlive(
963 rcx, infer::CallRcvr(r.span),
964 r.id, callee_region);
965 if implicitly_ref_args {
966 link_by_ref(rcx, &*r, callee_scope);
971 /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being
972 /// dereferenced, the lifetime of the pointer includes the deref expr.
973 fn constrain_autoderefs<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
974 deref_expr: &hir::Expr,
976 mut derefd_ty: Ty<'tcx>)
978 debug!("constrain_autoderefs(deref_expr={:?}, derefs={}, derefd_ty={:?})",
983 let s_deref_expr = rcx.tcx().region_maps.node_extent(deref_expr.id);
984 let r_deref_expr = ty::ReScope(s_deref_expr);
986 let method_call = MethodCall::autoderef(deref_expr.id, i as u32);
987 debug!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call, derefs);
989 let method = rcx.fcx.inh.tables.borrow().method_map.get(&method_call).map(|m| m.clone());
991 derefd_ty = match method {
993 debug!("constrain_autoderefs: #{} is overloaded, method={:?}",
996 let origin = infer::ParameterOrigin::OverloadedDeref;
997 substs_wf_in_scope(rcx, origin, method.substs, deref_expr.span, r_deref_expr);
999 // Treat overloaded autoderefs as if an AutoRef adjustment
1000 // was applied on the base type, as that is always the case.
1001 let fn_sig = method.ty.fn_sig();
1002 let fn_sig = // late-bound regions should have been instantiated
1003 rcx.tcx().no_late_bound_regions(fn_sig).unwrap();
1004 let self_ty = fn_sig.inputs[0];
1005 let (m, r) = match self_ty.sty {
1006 ty::TyRef(r, ref m) => (m.mutbl, r),
1008 rcx.tcx().sess.span_bug(
1010 &format!("bad overloaded deref type {:?}",
1015 debug!("constrain_autoderefs: receiver r={:?} m={:?}",
1019 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1020 let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i));
1021 debug!("constrain_autoderefs: self_cmt={:?}",
1023 link_region(rcx, deref_expr.span, r,
1024 ty::BorrowKind::from_mutbl(m), self_cmt);
1027 // Specialized version of constrain_call.
1028 type_must_outlive(rcx, infer::CallRcvr(deref_expr.span),
1029 self_ty, r_deref_expr);
1030 match fn_sig.output {
1031 ty::FnConverging(return_type) => {
1032 type_must_outlive(rcx, infer::CallReturn(deref_expr.span),
1033 return_type, r_deref_expr);
1036 ty::FnDiverging => unreachable!()
1042 if let ty::TyRef(r_ptr, _) = derefd_ty.sty {
1043 mk_subregion_due_to_dereference(rcx, deref_expr.span,
1044 r_deref_expr, *r_ptr);
1047 match derefd_ty.builtin_deref(true, ty::NoPreference) {
1048 Some(mt) => derefd_ty = mt.ty,
1049 /* if this type can't be dereferenced, then there's already an error
1050 in the session saying so. Just bail out for now */
1056 pub fn mk_subregion_due_to_dereference(rcx: &mut Rcx,
1058 minimum_lifetime: ty::Region,
1059 maximum_lifetime: ty::Region) {
1060 rcx.fcx.mk_subr(infer::DerefPointer(deref_span),
1061 minimum_lifetime, maximum_lifetime)
1064 fn check_safety_of_rvalue_destructor_if_necessary<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
1068 Categorization::Rvalue(region) => {
1070 ty::ReScope(rvalue_scope) => {
1071 let typ = rcx.resolve_type(cmt.ty);
1072 dropck::check_safety_of_destructor_if_necessary(rcx,
1082 &format!("unexpected rvalue region in rvalue \
1083 destructor safety checking: `{:?}`",
1092 /// Invoked on any index expression that occurs. Checks that if this is a slice being indexed, the
1093 /// lifetime of the pointer includes the deref expr.
1094 fn constrain_index<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
1095 index_expr: &hir::Expr,
1096 indexed_ty: Ty<'tcx>)
1098 debug!("constrain_index(index_expr=?, indexed_ty={}",
1099 rcx.fcx.infcx().ty_to_string(indexed_ty));
1101 let r_index_expr = ty::ReScope(rcx.tcx().region_maps.node_extent(index_expr.id));
1102 if let ty::TyRef(r_ptr, mt) = indexed_ty.sty {
1104 ty::TySlice(_) | ty::TyStr => {
1105 rcx.fcx.mk_subr(infer::IndexSlice(index_expr.span),
1106 r_index_expr, *r_ptr);
1113 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1114 /// adjustments) are valid for at least `minimum_lifetime`
1115 fn type_of_node_must_outlive<'a, 'tcx>(
1116 rcx: &mut Rcx<'a, 'tcx>,
1117 origin: infer::SubregionOrigin<'tcx>,
1119 minimum_lifetime: ty::Region)
1121 let tcx = rcx.fcx.tcx();
1123 // Try to resolve the type. If we encounter an error, then typeck
1124 // is going to fail anyway, so just stop here and let typeck
1125 // report errors later on in the writeback phase.
1126 let ty0 = rcx.resolve_node_type(id);
1127 let ty = ty0.adjust(tcx, origin.span(), id,
1128 rcx.fcx.inh.tables.borrow().adjustments.get(&id),
1129 |method_call| rcx.resolve_method_type(method_call));
1130 debug!("constrain_regions_in_type_of_node(\
1131 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
1133 id, minimum_lifetime);
1134 type_must_outlive(rcx, origin, ty, minimum_lifetime);
1137 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1138 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1139 fn link_addr_of(rcx: &mut Rcx, expr: &hir::Expr,
1140 mutability: hir::Mutability, base: &hir::Expr) {
1141 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
1144 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1145 ignore_err!(mc.cat_expr(base))
1148 debug!("link_addr_of: cmt={:?}", cmt);
1150 link_region_from_node_type(rcx, expr.span, expr.id, mutability, cmt);
1153 /// Computes the guarantors for any ref bindings in a `let` and
1154 /// then ensures that the lifetime of the resulting pointer is
1155 /// linked to the lifetime of the initialization expression.
1156 fn link_local(rcx: &Rcx, local: &hir::Local) {
1157 debug!("regionck::for_local()");
1158 let init_expr = match local.init {
1160 Some(ref expr) => &**expr,
1162 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1163 let discr_cmt = ignore_err!(mc.cat_expr(init_expr));
1164 link_pattern(rcx, mc, discr_cmt, &*local.pat);
1167 /// Computes the guarantors for any ref bindings in a match and
1168 /// then ensures that the lifetime of the resulting pointer is
1169 /// linked to the lifetime of its guarantor (if any).
1170 fn link_match(rcx: &Rcx, discr: &hir::Expr, arms: &[hir::Arm]) {
1171 debug!("regionck::for_match()");
1172 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1173 let discr_cmt = ignore_err!(mc.cat_expr(discr));
1174 debug!("discr_cmt={:?}", discr_cmt);
1176 for root_pat in &arm.pats {
1177 link_pattern(rcx, mc, discr_cmt.clone(), &**root_pat);
1182 /// Computes the guarantors for any ref bindings in a match and
1183 /// then ensures that the lifetime of the resulting pointer is
1184 /// linked to the lifetime of its guarantor (if any).
1185 fn link_fn_args(rcx: &Rcx, body_scope: CodeExtent, args: &[hir::Arg]) {
1186 debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1187 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1189 let arg_ty = rcx.fcx.node_ty(arg.id);
1190 let re_scope = ty::ReScope(body_scope);
1191 let arg_cmt = mc.cat_rvalue(arg.id, arg.ty.span, re_scope, arg_ty);
1192 debug!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1196 link_pattern(rcx, mc, arg_cmt, &*arg.pat);
1200 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found in the discriminant, if
1202 fn link_pattern<'t, 'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1203 mc: mc::MemCategorizationContext<'t, 'a, 'tcx>,
1204 discr_cmt: mc::cmt<'tcx>,
1205 root_pat: &hir::Pat) {
1206 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1209 let _ = mc.cat_pattern(discr_cmt, root_pat, |mc, sub_cmt, sub_pat| {
1210 match sub_pat.node {
1212 hir::PatIdent(hir::BindByRef(mutbl), _, _) => {
1213 link_region_from_node_type(
1214 rcx, sub_pat.span, sub_pat.id,
1218 // `[_, ..slice, _]` pattern
1219 hir::PatVec(_, Some(ref slice_pat), _) => {
1220 match mc.cat_slice_pattern(sub_cmt, &**slice_pat) {
1221 Ok((slice_cmt, slice_mutbl, slice_r)) => {
1222 link_region(rcx, sub_pat.span, &slice_r,
1223 ty::BorrowKind::from_mutbl(slice_mutbl),
1234 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1236 fn link_autoref(rcx: &Rcx,
1239 autoref: &adjustment::AutoRef)
1241 debug!("link_autoref(autoref={:?})", autoref);
1242 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1243 let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs));
1244 debug!("expr_cmt={:?}", expr_cmt);
1247 adjustment::AutoPtr(r, m) => {
1248 link_region(rcx, expr.span, r,
1249 ty::BorrowKind::from_mutbl(m), expr_cmt);
1252 adjustment::AutoUnsafe(m) => {
1253 let r = ty::ReScope(rcx.tcx().region_maps.node_extent(expr.id));
1254 link_region(rcx, expr.span, &r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1259 /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and
1260 /// must outlive `callee_scope`.
1261 fn link_by_ref(rcx: &Rcx,
1263 callee_scope: CodeExtent) {
1264 debug!("link_by_ref(expr={:?}, callee_scope={:?})",
1265 expr, callee_scope);
1266 let mc = mc::MemCategorizationContext::new(rcx.fcx.infcx());
1267 let expr_cmt = ignore_err!(mc.cat_expr(expr));
1268 let borrow_region = ty::ReScope(callee_scope);
1269 link_region(rcx, expr.span, &borrow_region, ty::ImmBorrow, expr_cmt);
1272 /// Like `link_region()`, except that the region is extracted from the type of `id`, which must be
1273 /// some reference (`&T`, `&str`, etc).
1274 fn link_region_from_node_type<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1277 mutbl: hir::Mutability,
1278 cmt_borrowed: mc::cmt<'tcx>) {
1279 debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1280 id, mutbl, cmt_borrowed);
1282 let rptr_ty = rcx.resolve_node_type(id);
1283 if let ty::TyRef(&r, _) = rptr_ty.sty {
1284 debug!("rptr_ty={}", rptr_ty);
1285 link_region(rcx, span, &r, ty::BorrowKind::from_mutbl(mutbl),
1290 /// Informs the inference engine that `borrow_cmt` is being borrowed with kind `borrow_kind` and
1291 /// lifetime `borrow_region`. In order to ensure borrowck is satisfied, this may create constraints
1292 /// between regions, as explained in `link_reborrowed_region()`.
1293 fn link_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1295 borrow_region: &ty::Region,
1296 borrow_kind: ty::BorrowKind,
1297 borrow_cmt: mc::cmt<'tcx>) {
1298 let mut borrow_cmt = borrow_cmt;
1299 let mut borrow_kind = borrow_kind;
1301 let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1302 type_must_outlive(rcx, origin, borrow_cmt.ty, *borrow_region);
1305 debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1309 match borrow_cmt.cat.clone() {
1310 Categorization::Deref(ref_cmt, _,
1311 mc::Implicit(ref_kind, ref_region)) |
1312 Categorization::Deref(ref_cmt, _,
1313 mc::BorrowedPtr(ref_kind, ref_region)) => {
1314 match link_reborrowed_region(rcx, span,
1315 borrow_region, borrow_kind,
1316 ref_cmt, ref_region, ref_kind,
1328 Categorization::Downcast(cmt_base, _) |
1329 Categorization::Deref(cmt_base, _, mc::Unique) |
1330 Categorization::Interior(cmt_base, _) => {
1331 // Borrowing interior or owned data requires the base
1332 // to be valid and borrowable in the same fashion.
1333 borrow_cmt = cmt_base;
1334 borrow_kind = borrow_kind;
1337 Categorization::Deref(_, _, mc::UnsafePtr(..)) |
1338 Categorization::StaticItem |
1339 Categorization::Upvar(..) |
1340 Categorization::Local(..) |
1341 Categorization::Rvalue(..) => {
1342 // These are all "base cases" with independent lifetimes
1343 // that are not subject to inference
1350 /// This is the most complicated case: the path being borrowed is
1351 /// itself the referent of a borrowed pointer. Let me give an
1352 /// example fragment of code to make clear(er) the situation:
1354 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1356 /// &'z *r // the reborrow has lifetime 'z
1358 /// Now, in this case, our primary job is to add the inference
1359 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1360 /// parameters in (roughly) terms of the example:
1362 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1363 /// borrow_region ^~ ref_region ^~
1364 /// borrow_kind ^~ ref_kind ^~
1367 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1369 /// Unfortunately, there are some complications beyond the simple
1370 /// scenario I just painted:
1372 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1373 /// case, we have two jobs. First, we are inferring whether this reference
1374 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1375 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1376 /// then `r` must be an `&mut` reference). Second, whenever we link
1377 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1378 /// case we adjust the cause to indicate that the reference being
1379 /// "reborrowed" is itself an upvar. This provides a nicer error message
1380 /// should something go wrong.
1382 /// 2. There may in fact be more levels of reborrowing. In the
1383 /// example, I said the borrow was like `&'z *r`, but it might
1384 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1385 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1386 /// and `'z <= 'b`. This is explained more below.
1388 /// The return value of this function indicates whether we need to
1389 /// recurse and process `ref_cmt` (see case 2 above).
1390 fn link_reborrowed_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1392 borrow_region: &ty::Region,
1393 borrow_kind: ty::BorrowKind,
1394 ref_cmt: mc::cmt<'tcx>,
1395 ref_region: ty::Region,
1396 mut ref_kind: ty::BorrowKind,
1398 -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1400 // Possible upvar ID we may need later to create an entry in the
1403 // Detect by-ref upvar `x`:
1404 let cause = match note {
1405 mc::NoteUpvarRef(ref upvar_id) => {
1406 let upvar_capture_map = &rcx.fcx.inh.tables.borrow_mut().upvar_capture_map;
1407 match upvar_capture_map.get(upvar_id) {
1408 Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1409 // The mutability of the upvar may have been modified
1410 // by the above adjustment, so update our local variable.
1411 ref_kind = upvar_borrow.kind;
1413 infer::ReborrowUpvar(span, *upvar_id)
1416 rcx.tcx().sess.span_bug(
1418 &format!("Illegal upvar id: {:?}",
1423 mc::NoteClosureEnv(ref upvar_id) => {
1424 // We don't have any mutability changes to propagate, but
1425 // we do want to note that an upvar reborrow caused this
1427 infer::ReborrowUpvar(span, *upvar_id)
1430 infer::Reborrow(span)
1434 debug!("link_reborrowed_region: {:?} <= {:?}",
1437 rcx.fcx.mk_subr(cause, *borrow_region, ref_region);
1439 // If we end up needing to recurse and establish a region link
1440 // with `ref_cmt`, calculate what borrow kind we will end up
1441 // needing. This will be used below.
1443 // One interesting twist is that we can weaken the borrow kind
1444 // when we recurse: to reborrow an `&mut` referent as mutable,
1445 // borrowck requires a unique path to the `&mut` reference but not
1446 // necessarily a *mutable* path.
1447 let new_borrow_kind = match borrow_kind {
1450 ty::MutBorrow | ty::UniqueImmBorrow =>
1454 // Decide whether we need to recurse and link any regions within
1455 // the `ref_cmt`. This is concerned for the case where the value
1456 // being reborrowed is in fact a borrowed pointer found within
1457 // another borrowed pointer. For example:
1459 // let p: &'b &'a mut T = ...;
1463 // What makes this case particularly tricky is that, if the data
1464 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1465 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1466 // (otherwise the user might mutate through the `&mut T` reference
1467 // after `'b` expires and invalidate the borrow we are looking at
1470 // So let's re-examine our parameters in light of this more
1471 // complicated (possible) scenario:
1473 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1474 // borrow_region ^~ ref_region ^~
1475 // borrow_kind ^~ ref_kind ^~
1478 // (Note that since we have not examined `ref_cmt.cat`, we don't
1479 // know whether this scenario has occurred; but I wanted to show
1480 // how all the types get adjusted.)
1483 // The reference being reborrowed is a sharable ref of
1484 // type `&'a T`. In this case, it doesn't matter where we
1485 // *found* the `&T` pointer, the memory it references will
1486 // be valid and immutable for `'a`. So we can stop here.
1488 // (Note that the `borrow_kind` must also be ImmBorrow or
1489 // else the user is borrowed imm memory as mut memory,
1490 // which means they'll get an error downstream in borrowck
1495 ty::MutBorrow | ty::UniqueImmBorrow => {
1496 // The reference being reborrowed is either an `&mut T` or
1497 // `&uniq T`. This is the case where recursion is needed.
1498 return Some((ref_cmt, new_borrow_kind));
1503 /// Checks that the values provided for type/region arguments in a given
1504 /// expression are well-formed and in-scope.
1505 pub fn substs_wf_in_scope<'a,'tcx>(rcx: &mut Rcx<'a,'tcx>,
1506 origin: infer::ParameterOrigin,
1507 substs: &Substs<'tcx>,
1509 expr_region: ty::Region) {
1510 debug!("substs_wf_in_scope(substs={:?}, \
1514 substs, expr_region, origin, expr_span);
1516 let origin = infer::ParameterInScope(origin, expr_span);
1518 for ®ion in substs.regions() {
1519 rcx.fcx.mk_subr(origin.clone(), expr_region, region);
1522 for &ty in &substs.types {
1523 let ty = rcx.resolve_type(ty);
1524 type_must_outlive(rcx, origin.clone(), ty, expr_region);
1528 /// Ensures that type is well-formed in `region`, which implies (among
1529 /// other things) that all borrowed data reachable via `ty` outlives
1531 pub fn type_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1532 origin: infer::SubregionOrigin<'tcx>,
1536 let ty = rcx.resolve_type(ty);
1538 debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})",
1543 assert!(!ty.has_escaping_regions());
1545 let components = ty::outlives::components(rcx.infcx(), ty);
1546 components_must_outlive(rcx, origin, components, region);
1549 fn components_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1550 origin: infer::SubregionOrigin<'tcx>,
1551 components: Vec<ty::outlives::Component<'tcx>>,
1554 for component in components {
1555 let origin = origin.clone();
1557 ty::outlives::Component::Region(region1) => {
1558 rcx.fcx.mk_subr(origin, region, region1);
1560 ty::outlives::Component::Param(param_ty) => {
1561 param_ty_must_outlive(rcx, origin, region, param_ty);
1563 ty::outlives::Component::Projection(projection_ty) => {
1564 projection_must_outlive(rcx, origin, region, projection_ty);
1566 ty::outlives::Component::EscapingProjection(subcomponents) => {
1567 components_must_outlive(rcx, origin, subcomponents, region);
1569 ty::outlives::Component::UnresolvedInferenceVariable(v) => {
1570 // ignore this, we presume it will yield an error
1571 // later, since if a type variable is not resolved by
1572 // this point it never will be
1573 rcx.tcx().sess.delay_span_bug(
1575 &format!("unresolved inference variable in outlives: {:?}", v));
1577 ty::outlives::Component::RFC1214(subcomponents) => {
1578 let suborigin = infer::RFC1214Subregion(Rc::new(origin));
1579 components_must_outlive(rcx, suborigin, subcomponents, region);
1585 fn param_ty_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1586 origin: infer::SubregionOrigin<'tcx>,
1588 param_ty: ty::ParamTy) {
1589 debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1590 region, param_ty, origin);
1592 let verify_bound = param_bound(rcx, param_ty);
1593 let generic = GenericKind::Param(param_ty);
1594 rcx.fcx.infcx().verify_generic_bound(origin, generic, region, verify_bound);
1597 fn projection_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1598 origin: infer::SubregionOrigin<'tcx>,
1600 projection_ty: ty::ProjectionTy<'tcx>)
1602 debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1603 region, projection_ty, origin);
1605 // This case is thorny for inference. The fundamental problem is
1606 // that there are many cases where we have choice, and inference
1607 // doesn't like choice (the current region inference in
1608 // particular). :) First off, we have to choose between using the
1609 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1610 // OutlivesProjectionComponent rules, any one of which is
1611 // sufficient. If there are no inference variables involved, it's
1612 // not hard to pick the right rule, but if there are, we're in a
1613 // bit of a catch 22: if we picked which rule we were going to
1614 // use, we could add constraints to the region inference graph
1615 // that make it apply, but if we don't add those constraints, the
1616 // rule might not apply (but another rule might). For now, we err
1617 // on the side of adding too few edges into the graph.
1619 // Compute the bounds we can derive from the environment or trait
1620 // definition. We know that the projection outlives all the
1621 // regions in this list.
1622 let env_bounds = projection_declared_bounds(rcx, origin.span(), projection_ty);
1624 debug!("projection_must_outlive: env_bounds={:?}",
1627 // If we know that the projection outlives 'static, then we're
1629 if env_bounds.contains(&ty::ReStatic) {
1630 debug!("projection_must_outlive: 'static as declared bound");
1634 // If declared bounds list is empty, the only applicable rule is
1635 // OutlivesProjectionComponent. If there are inference variables,
1636 // then, we can break down the outlives into more primitive
1637 // components without adding unnecessary edges.
1639 // If there are *no* inference variables, however, we COULD do
1640 // this, but we choose not to, because the error messages are less
1641 // good. For example, a requirement like `T::Item: 'r` would be
1642 // translated to a requirement that `T: 'r`; when this is reported
1643 // to the user, it will thus say "T: 'r must hold so that T::Item:
1644 // 'r holds". But that makes it sound like the only way to fix
1645 // the problem is to add `T: 'r`, which isn't true. So, if there are no
1646 // inference variables, we use a verify constraint instead of adding
1647 // edges, which winds up enforcing the same condition.
1649 projection_ty.trait_ref.substs.types.iter().any(|t| t.needs_infer()) ||
1650 projection_ty.trait_ref.substs.regions().iter().any(|r| r.needs_infer())
1652 if env_bounds.is_empty() && needs_infer {
1653 debug!("projection_must_outlive: no declared bounds");
1655 for &component_ty in &projection_ty.trait_ref.substs.types {
1656 type_must_outlive(rcx, origin.clone(), component_ty, region);
1659 for &r in projection_ty.trait_ref.substs.regions() {
1660 rcx.fcx.mk_subr(origin.clone(), region, r);
1666 // If we find that there is a unique declared bound `'b`, and this bound
1667 // appears in the trait reference, then the best action is to require that `'b:'r`,
1668 // so do that. This is best no matter what rule we use:
1670 // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1671 // the requirement that `'b:'r`
1672 // - OutlivesProjectionComponent: this would require `'b:'r` in addition to other conditions
1673 if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) {
1674 let unique_bound = env_bounds[0];
1675 debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound);
1676 if projection_ty.trait_ref.substs.regions()
1678 .any(|r| env_bounds.contains(r))
1680 debug!("projection_must_outlive: unique declared bound appears in trait ref");
1681 rcx.fcx.mk_subr(origin.clone(), region, unique_bound);
1686 // Fallback to verifying after the fact that there exists a
1687 // declared bound, or that all the components appearing in the
1688 // projection outlive; in some cases, this may add insufficient
1689 // edges into the inference graph, leading to inference failures
1690 // even though a satisfactory solution exists.
1691 let verify_bound = projection_bound(rcx, origin.span(), env_bounds, projection_ty);
1692 let generic = GenericKind::Projection(projection_ty);
1693 rcx.fcx.infcx().verify_generic_bound(origin, generic.clone(), region, verify_bound);
1696 fn type_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, span: Span, ty: Ty<'tcx>) -> VerifyBound {
1701 ty::TyProjection(data) => {
1702 let declared_bounds = projection_declared_bounds(rcx, span, data);
1703 projection_bound(rcx, span, declared_bounds, data)
1706 recursive_type_bound(rcx, span, ty)
1711 fn param_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, param_ty: ty::ParamTy) -> VerifyBound {
1712 let param_env = &rcx.infcx().parameter_environment;
1714 debug!("param_bound(param_ty={:?})",
1717 let mut param_bounds = declared_generic_bounds_from_env(rcx, GenericKind::Param(param_ty));
1719 // Add in the default bound of fn body that applies to all in
1720 // scope type parameters:
1721 param_bounds.push(param_env.implicit_region_bound);
1723 VerifyBound::AnyRegion(param_bounds)
1726 fn projection_declared_bounds<'a, 'tcx>(rcx: &Rcx<'a,'tcx>,
1728 projection_ty: ty::ProjectionTy<'tcx>)
1731 // First assemble bounds from where clauses and traits.
1733 let mut declared_bounds =
1734 declared_generic_bounds_from_env(rcx, GenericKind::Projection(projection_ty));
1736 declared_bounds.push_all(
1737 &declared_projection_bounds_from_trait(rcx, span, projection_ty));
1742 fn projection_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1744 declared_bounds: Vec<ty::Region>,
1745 projection_ty: ty::ProjectionTy<'tcx>)
1747 debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1748 declared_bounds, projection_ty);
1750 // see the extensive comment in projection_must_outlive
1752 let ty = rcx.tcx().mk_projection(projection_ty.trait_ref, projection_ty.item_name);
1753 let recursive_bound = recursive_type_bound(rcx, span, ty);
1755 VerifyBound::AnyRegion(declared_bounds).or(recursive_bound)
1758 fn recursive_type_bound<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1762 let mut bounds = vec![];
1764 for subty in ty.walk_shallow() {
1765 bounds.push(type_bound(rcx, span, subty));
1768 let mut regions = ty.regions();
1769 regions.retain(|r| !r.is_bound()); // ignore late-bound regions
1770 bounds.push(VerifyBound::AllRegions(regions));
1772 // remove bounds that must hold, since they are not interesting
1773 bounds.retain(|b| !b.must_hold());
1775 if bounds.len() == 1 {
1776 bounds.pop().unwrap()
1778 VerifyBound::AllBounds(bounds)
1782 fn declared_generic_bounds_from_env<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1783 generic: GenericKind<'tcx>)
1786 let param_env = &rcx.infcx().parameter_environment;
1788 // To start, collect bounds from user:
1789 let mut param_bounds = rcx.tcx().required_region_bounds(generic.to_ty(rcx.tcx()),
1790 param_env.caller_bounds.clone());
1792 // Next, collect regions we scraped from the well-formedness
1793 // constraints in the fn signature. To do that, we walk the list
1794 // of known relations from the fn ctxt.
1796 // This is crucial because otherwise code like this fails:
1798 // fn foo<'a, A>(x: &'a A) { x.bar() }
1800 // The problem is that the type of `x` is `&'a A`. To be
1801 // well-formed, then, A must be lower-generic by `'a`, but we
1802 // don't know that this holds from first principles.
1803 for &(r, p) in &rcx.region_bound_pairs {
1804 debug!("generic={:?} p={:?}",
1808 param_bounds.push(r);
1815 fn declared_projection_bounds_from_trait<'a,'tcx>(rcx: &Rcx<'a, 'tcx>,
1817 projection_ty: ty::ProjectionTy<'tcx>)
1821 let tcx = fcx.tcx();
1822 let infcx = fcx.infcx();
1824 debug!("projection_bounds(projection_ty={:?})",
1827 let ty = tcx.mk_projection(projection_ty.trait_ref.clone(), projection_ty.item_name);
1829 // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1830 // in looking for a trait definition like:
1833 // trait SomeTrait<'a> {
1834 // type SomeType : 'a;
1838 // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1839 let trait_predicates = tcx.lookup_predicates(projection_ty.trait_ref.def_id);
1840 let predicates = trait_predicates.predicates.as_slice().to_vec();
1841 traits::elaborate_predicates(tcx, predicates)
1842 .filter_map(|predicate| {
1843 // we're only interesting in `T : 'a` style predicates:
1844 let outlives = match predicate {
1845 ty::Predicate::TypeOutlives(data) => data,
1846 _ => { return None; }
1849 debug!("projection_bounds: outlives={:?} (1)",
1852 // apply the substitutions (and normalize any projected types)
1853 let outlives = fcx.instantiate_type_scheme(span,
1854 projection_ty.trait_ref.substs,
1857 debug!("projection_bounds: outlives={:?} (2)",
1860 let region_result = infcx.commit_if_ok(|_| {
1862 infcx.replace_late_bound_regions_with_fresh_var(
1864 infer::AssocTypeProjection(projection_ty.item_name),
1867 debug!("projection_bounds: outlives={:?} (3)",
1870 // check whether this predicate applies to our current projection
1871 match infer::mk_eqty(infcx, false, TypeOrigin::Misc(span), ty, outlives.0) {
1872 Ok(()) => { Ok(outlives.1) }
1873 Err(_) => { Err(()) }
1877 debug!("projection_bounds: region_result={:?}",