1 //! ### Inferring borrow kinds for upvars
3 //! Whenever there is a closure expression, we need to determine how each
4 //! upvar is used. We do this by initially assigning each upvar an
5 //! immutable "borrow kind" (see `ty::BorrowKind` for details) and then
6 //! "escalating" the kind as needed. The borrow kind proceeds according to
7 //! the following lattice:
9 //! ty::ImmBorrow -> ty::UniqueImmBorrow -> ty::MutBorrow
11 //! So, for example, if we see an assignment `x = 5` to an upvar `x`, we
12 //! will promote its borrow kind to mutable borrow. If we see an `&mut x`
13 //! we'll do the same. Naturally, this applies not just to the upvar, but
14 //! to everything owned by `x`, so the result is the same for something
15 //! like `x.f = 5` and so on (presuming `x` is not a borrowed pointer to a
16 //! struct). These adjustments are performed in
17 //! `adjust_upvar_borrow_kind()` (you can trace backwards through the code
20 //! The fact that we are inferring borrow kinds as we go results in a
21 //! semi-hacky interaction with mem-categorization. In particular,
22 //! mem-categorization will query the current borrow kind as it
23 //! categorizes, and we'll return the *current* value, but this may get
24 //! adjusted later. Therefore, in this module, we generally ignore the
25 //! borrow kind (and derived mutabilities) that are returned from
26 //! mem-categorization, since they may be inaccurate. (Another option
27 //! would be to use a unification scheme, where instead of returning a
28 //! concrete borrow kind like `ty::ImmBorrow`, we return a
29 //! `ty::InferBorrow(upvar_id)` or something like that, but this would
30 //! then mean that all later passes would have to check for these figments
31 //! and report an error, and it just seems like more mess in the end.)
35 use crate::middle::expr_use_visitor as euv;
36 use crate::middle::mem_categorization as mc;
37 use crate::middle::mem_categorization::Categorization;
39 use rustc::hir::def_id::DefId;
40 use rustc::hir::def_id::LocalDefId;
41 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
42 use rustc::infer::UpvarRegion;
43 use rustc::ty::{self, Ty, TyCtxt, UpvarSubsts};
47 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
48 pub fn closure_analyze(&self, body: &'gcx hir::Body) {
49 InferBorrowKindVisitor { fcx: self }.visit_body(body);
51 // it's our job to process these.
52 assert!(self.deferred_call_resolutions.borrow().is_empty());
56 struct InferBorrowKindVisitor<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
57 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
60 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for InferBorrowKindVisitor<'a, 'gcx, 'tcx> {
61 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
62 NestedVisitorMap::None
65 fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
66 if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.node {
67 let body = self.fcx.tcx.hir().body(body_id);
68 self.visit_body(body);
70 .analyze_closure(expr.hir_id, expr.span, body, cc);
73 intravisit::walk_expr(self, expr);
77 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
80 closure_hir_id: hir::HirId,
83 capture_clause: hir::CaptureClause,
86 * Analysis starting point.
90 "analyze_closure(id={:?}, body.id={:?})",
95 // Extract the type of the closure.
96 let ty = self.node_ty(closure_hir_id);
97 let (closure_def_id, substs) = match ty.sty {
98 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
99 ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
101 // #51714: skip analysis when we have already encountered type errors
107 "type of closure expr {:?} is not a closure {:?}",
114 let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
115 if self.closure_kind(closure_def_id, closure_substs).is_none() {
124 if let Some(upvars) = self.tcx.upvars(closure_def_id) {
125 let mut upvar_list: Vec<ty::UpvarId> = Vec::with_capacity(upvars.len());
126 for upvar in upvars.iter() {
127 let upvar_id = ty::UpvarId {
128 var_path: ty::UpvarPath {
129 hir_id: upvar.var_id(),
131 closure_expr_id: LocalDefId::from_def_id(closure_def_id),
133 debug!("seed upvar_id {:?}", upvar_id);
134 // Adding the upvar Id to the list of Upvars, which will be added
135 // to the map for the closure at the end of the for loop.
136 upvar_list.push(upvar_id);
138 let capture_kind = match capture_clause {
139 hir::CaptureByValue => ty::UpvarCapture::ByValue,
140 hir::CaptureByRef => {
141 let origin = UpvarRegion(upvar_id, span);
142 let upvar_region = self.next_region_var(origin);
143 let upvar_borrow = ty::UpvarBorrow {
145 region: upvar_region,
147 ty::UpvarCapture::ByRef(upvar_borrow)
154 .insert(upvar_id, capture_kind);
156 // Add the vector of upvars to the map keyed with the closure id.
157 // This gives us an easier access to them without having to call
158 // tcx.upvars again..
159 if !upvar_list.is_empty() {
163 .insert(closure_def_id, upvar_list);
167 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
168 let region_scope_tree = &self.tcx.region_scope_tree(body_owner_def_id);
169 let mut delegate = InferBorrowKind {
171 closure_def_id: closure_def_id,
172 current_closure_kind: ty::ClosureKind::LATTICE_BOTTOM,
173 current_origin: None,
174 adjust_upvar_captures: ty::UpvarCaptureMap::default(),
176 euv::ExprUseVisitor::with_infer(
181 &self.tables.borrow(),
185 if let Some(closure_substs) = infer_kind {
186 // Unify the (as yet unbound) type variable in the closure
187 // substs with the kind we inferred.
188 let inferred_kind = delegate.current_closure_kind;
189 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx);
190 self.demand_eqtype(span, inferred_kind.to_ty(self.tcx), closure_kind_ty);
192 // If we have an origin, store it.
193 if let Some(origin) = delegate.current_origin {
196 .closure_kind_origins_mut()
197 .insert(closure_hir_id, origin);
204 .extend(delegate.adjust_upvar_captures);
206 // Now that we've analyzed the closure, we know how each
207 // variable is borrowed, and we know what traits the closure
208 // implements (Fn vs FnMut etc). We now have some updates to do
209 // with that information.
211 // Note that no closure type C may have an upvar of type C
212 // (though it may reference itself via a trait object). This
213 // results from the desugaring of closures to a struct like
214 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
215 // C, then the type would have infinite size (and the
216 // inference algorithm will reject it).
218 // Equate the type variables for the upvars with the actual types.
219 let final_upvar_tys = self.final_upvar_tys(closure_hir_id);
221 "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
222 closure_hir_id, substs, final_upvar_tys
224 for (upvar_ty, final_upvar_ty) in substs
225 .upvar_tys(closure_def_id, self.tcx)
226 .zip(final_upvar_tys)
228 self.demand_suptype(span, upvar_ty, final_upvar_ty);
231 // If we are also inferred the closure kind here,
232 // process any deferred resolutions.
233 let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
234 for deferred_call_resolution in deferred_call_resolutions {
235 deferred_call_resolution.resolve(self);
239 // Returns a list of `ClosureUpvar`s for each upvar.
240 fn final_upvar_tys(&self, closure_id: hir::HirId) -> Vec<Ty<'tcx>> {
241 // Presently an unboxed closure type cannot "escape" out of a
242 // function, so we will only encounter ones that originated in the
243 // local crate or were inlined into it along with some function.
244 // This may change if abstract return types of some sort are
247 let closure_def_id = tcx.hir().local_def_id_from_hir_id(closure_id);
249 tcx.upvars(closure_def_id).iter().flat_map(|upvars| {
253 let var_hir_id = upvar.var_id();
254 let upvar_ty = self.node_ty(var_hir_id);
255 let upvar_id = ty::UpvarId {
256 var_path: ty::UpvarPath { hir_id: var_hir_id },
257 closure_expr_id: LocalDefId::from_def_id(closure_def_id),
259 let capture = self.tables.borrow().upvar_capture(upvar_id);
262 "var_id={:?} upvar_ty={:?} capture={:?}",
263 var_hir_id, upvar_ty, capture
267 ty::UpvarCapture::ByValue => upvar_ty,
268 ty::UpvarCapture::ByRef(borrow) => tcx.mk_ref(
272 mutbl: borrow.kind.to_mutbl_lossy(),
282 struct InferBorrowKind<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
283 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
285 // The def-id of the closure whose kind and upvar accesses are being inferred.
286 closure_def_id: DefId,
288 // The kind that we have inferred that the current closure
289 // requires. Note that we *always* infer a minimal kind, even if
290 // we don't always *use* that in the final result (i.e., sometimes
291 // we've taken the closure kind from the expectations instead, and
292 // for generators we don't even implement the closure traits
294 current_closure_kind: ty::ClosureKind,
296 // If we modified `current_closure_kind`, this field contains a `Some()` with the
297 // variable access that caused us to do so.
298 current_origin: Option<(Span, ast::Name)>,
300 // For each upvar that we access, we track the minimal kind of
301 // access we need (ref, ref mut, move, etc).
302 adjust_upvar_captures: ty::UpvarCaptureMap<'tcx>,
305 impl<'a, 'gcx, 'tcx> InferBorrowKind<'a, 'gcx, 'tcx> {
306 fn adjust_upvar_borrow_kind_for_consume(
308 cmt: &mc::cmt_<'tcx>,
309 mode: euv::ConsumeMode,
312 "adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
316 // we only care about moves
324 let tcx = self.fcx.tcx;
326 // watch out for a move of the deref of a borrowed pointer;
327 // for that to be legal, the upvar would have to be borrowed
329 let guarantor = cmt.guarantor();
331 "adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
335 "adjust_upvar_borrow_kind_for_consume: guarantor.cat={:?}",
338 if let Categorization::Deref(_, mc::BorrowedPtr(..)) = guarantor.cat {
340 "adjust_upvar_borrow_kind_for_consume: found deref with note {:?}",
343 match guarantor.note {
344 mc::NoteUpvarRef(upvar_id) => {
346 "adjust_upvar_borrow_kind_for_consume: \
347 setting upvar_id={:?} to by value",
351 // to move out of an upvar, this must be a FnOnce closure
352 self.adjust_closure_kind(
353 upvar_id.closure_expr_id,
354 ty::ClosureKind::FnOnce,
356 var_name(tcx, upvar_id.var_path.hir_id),
359 self.adjust_upvar_captures
360 .insert(upvar_id, ty::UpvarCapture::ByValue);
362 mc::NoteClosureEnv(upvar_id) => {
363 // we get just a closureenv ref if this is a
364 // `move` closure, or if the upvar has already
365 // been inferred to by-value. In any case, we
366 // must still adjust the kind of the closure
367 // to be a FnOnce closure to permit moves out
368 // of the environment.
369 self.adjust_closure_kind(
370 upvar_id.closure_expr_id,
371 ty::ClosureKind::FnOnce,
373 var_name(tcx, upvar_id.var_path.hir_id),
376 mc::NoteIndex | mc::NoteNone => {}
381 /// Indicates that `cmt` is being directly mutated (e.g., assigned
382 /// to). If cmt contains any by-ref upvars, this implies that
383 /// those upvars must be borrowed using an `&mut` borrow.
384 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: &mc::cmt_<'tcx>) {
385 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})", cmt);
387 match cmt.cat.clone() {
388 Categorization::Deref(base, mc::Unique)
389 | Categorization::Interior(base, _)
390 | Categorization::Downcast(base, _) => {
391 // Interior or owned data is mutable if base is
392 // mutable, so iterate to the base.
393 self.adjust_upvar_borrow_kind_for_mut(&base);
396 Categorization::Deref(base, mc::BorrowedPtr(..)) => {
397 if !self.try_adjust_upvar_deref(cmt, ty::MutBorrow) {
398 // assignment to deref of an `&mut`
399 // borrowed pointer implies that the
400 // pointer itself must be unique, but not
401 // necessarily *mutable*
402 self.adjust_upvar_borrow_kind_for_unique(&base);
406 Categorization::Deref(_, mc::UnsafePtr(..))
407 | Categorization::StaticItem
408 | Categorization::ThreadLocal(..)
409 | Categorization::Rvalue(..)
410 | Categorization::Local(_)
411 | Categorization::Upvar(..) => {
417 fn adjust_upvar_borrow_kind_for_unique(&mut self, cmt: &mc::cmt_<'tcx>) {
418 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})", cmt);
420 match cmt.cat.clone() {
421 Categorization::Deref(base, mc::Unique)
422 | Categorization::Interior(base, _)
423 | Categorization::Downcast(base, _) => {
424 // Interior or owned data is unique if base is
426 self.adjust_upvar_borrow_kind_for_unique(&base);
429 Categorization::Deref(base, mc::BorrowedPtr(..)) => {
430 if !self.try_adjust_upvar_deref(cmt, ty::UniqueImmBorrow) {
431 // for a borrowed pointer to be unique, its
432 // base must be unique
433 self.adjust_upvar_borrow_kind_for_unique(&base);
437 Categorization::Deref(_, mc::UnsafePtr(..))
438 | Categorization::StaticItem
439 | Categorization::ThreadLocal(..)
440 | Categorization::Rvalue(..)
441 | Categorization::Local(_)
442 | Categorization::Upvar(..) => {}
446 fn try_adjust_upvar_deref(
448 cmt: &mc::cmt_<'tcx>,
449 borrow_kind: ty::BorrowKind,
451 assert!(match borrow_kind {
452 ty::MutBorrow => true,
453 ty::UniqueImmBorrow => true,
455 // imm borrows never require adjusting any kinds, so we don't wind up here
456 ty::ImmBorrow => false,
459 let tcx = self.fcx.tcx;
462 mc::NoteUpvarRef(upvar_id) => {
463 // if this is an implicit deref of an
464 // upvar, then we need to modify the
465 // borrow_kind of the upvar to make sure it
466 // is inferred to mutable if necessary
467 self.adjust_upvar_borrow_kind(upvar_id, borrow_kind);
469 // also need to be in an FnMut closure since this is not an ImmBorrow
470 self.adjust_closure_kind(
471 upvar_id.closure_expr_id,
472 ty::ClosureKind::FnMut,
474 var_name(tcx, upvar_id.var_path.hir_id),
479 mc::NoteClosureEnv(upvar_id) => {
480 // this kind of deref occurs in a `move` closure, or
481 // for a by-value upvar; in either case, to mutate an
482 // upvar, we need to be an FnMut closure
483 self.adjust_closure_kind(
484 upvar_id.closure_expr_id,
485 ty::ClosureKind::FnMut,
487 var_name(tcx, upvar_id.var_path.hir_id),
492 mc::NoteIndex | mc::NoteNone => false,
496 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
497 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
498 /// moving from left to right as needed (but never right to left).
499 /// Here the argument `mutbl` is the borrow_kind that is required by
500 /// some particular use.
501 fn adjust_upvar_borrow_kind(&mut self, upvar_id: ty::UpvarId, kind: ty::BorrowKind) {
502 let upvar_capture = self
503 .adjust_upvar_captures
506 .unwrap_or_else(|| self.fcx.tables.borrow().upvar_capture(upvar_id));
508 "adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
509 upvar_id, upvar_capture, kind
512 match upvar_capture {
513 ty::UpvarCapture::ByValue => {
514 // Upvar is already by-value, the strongest criteria.
516 ty::UpvarCapture::ByRef(mut upvar_borrow) => {
517 match (upvar_borrow.kind, kind) {
519 (ty::ImmBorrow, ty::UniqueImmBorrow)
520 | (ty::ImmBorrow, ty::MutBorrow)
521 | (ty::UniqueImmBorrow, ty::MutBorrow) => {
522 upvar_borrow.kind = kind;
523 self.adjust_upvar_captures
524 .insert(upvar_id, ty::UpvarCapture::ByRef(upvar_borrow));
527 (ty::ImmBorrow, ty::ImmBorrow)
528 | (ty::UniqueImmBorrow, ty::ImmBorrow)
529 | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
530 | (ty::MutBorrow, _) => {}
536 fn adjust_closure_kind(
538 closure_id: LocalDefId,
539 new_kind: ty::ClosureKind,
544 "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, var_name={})",
545 closure_id, new_kind, upvar_span, var_name
548 // Is this the closure whose kind is currently being inferred?
549 if closure_id.to_def_id() != self.closure_def_id {
550 debug!("adjust_closure_kind: not current closure");
554 // closures start out as `Fn`.
555 let existing_kind = self.current_closure_kind;
558 "adjust_closure_kind: closure_id={:?}, existing_kind={:?}, new_kind={:?}",
559 closure_id, existing_kind, new_kind
562 match (existing_kind, new_kind) {
563 (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
564 | (ty::ClosureKind::FnMut, ty::ClosureKind::Fn)
565 | (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut)
566 | (ty::ClosureKind::FnOnce, _) => {
570 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut)
571 | (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce)
572 | (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
573 // new kind is stronger than the old kind
574 self.current_closure_kind = new_kind;
575 self.current_origin = Some((upvar_span, var_name));
581 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'gcx, 'tcx> {
584 _consume_id: hir::HirId,
586 cmt: &mc::cmt_<'tcx>,
587 mode: euv::ConsumeMode,
589 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
590 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
595 _matched_pat: &hir::Pat,
596 _cmt: &mc::cmt_<'tcx>,
597 _mode: euv::MatchMode,
603 _consume_pat: &hir::Pat,
604 cmt: &mc::cmt_<'tcx>,
605 mode: euv::ConsumeMode,
607 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
608 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
613 borrow_id: hir::HirId,
615 cmt: &mc::cmt_<'tcx>,
616 _loan_region: ty::Region<'tcx>,
618 _loan_cause: euv::LoanCause,
621 "borrow(borrow_id={}, cmt={:?}, bk={:?})",
627 ty::UniqueImmBorrow => {
628 self.adjust_upvar_borrow_kind_for_unique(cmt);
631 self.adjust_upvar_borrow_kind_for_mut(cmt);
636 fn decl_without_init(&mut self, _id: hir::HirId, _span: Span) {}
640 _assignment_id: hir::HirId,
641 _assignment_span: Span,
642 assignee_cmt: &mc::cmt_<'tcx>,
643 _mode: euv::MutateMode,
645 debug!("mutate(assignee_cmt={:?})", assignee_cmt);
647 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);
651 fn var_name(tcx: TyCtxt<'_, '_, '_>, var_hir_id: hir::HirId) -> ast::Name {
652 tcx.hir().name_by_hir_id(var_hir_id)